返回介绍

solution / 2400-2499 / 2417.Closest Fair Integer / README_EN

发布于 2024-06-17 01:03:06 字数 3489 浏览 0 评论 0 收藏 0

2417. Closest Fair Integer

中文文档

Description

You are given a positive integer n.

We call an integer k fair if the number of even digits in k is equal to the number of odd digits in it.

Return _the smallest fair integer that is greater than or equal to _n.

 

Example 1:

Input: n = 2
Output: 10
Explanation: The smallest fair integer that is greater than or equal to 2 is 10.
10 is fair because it has an equal number of even and odd digits (one odd digit and one even digit).

Example 2:

Input: n = 403
Output: 1001
Explanation: The smallest fair integer that is greater than or equal to 403 is 1001.
1001 is fair because it has an equal number of even and odd digits (two odd digits and two even digits).

 

Constraints:

  • 1 <= n <= 109

Solutions

Solution 1

class Solution:
  def closestFair(self, n: int) -> int:
    a = b = k = 0
    t = n
    while t:
      if (t % 10) & 1:
        a += 1
      else:
        b += 1
      t //= 10
      k += 1
    if k & 1:
      x = 10**k
      y = int('1' * (k >> 1) or '0')
      return x + y
    if a == b:
      return n
    return self.closestFair(n + 1)
class Solution {
  public int closestFair(int n) {
    int a = 0, b = 0;
    int k = 0, t = n;
    while (t > 0) {
      if ((t % 10) % 2 == 1) {
        ++a;
      } else {
        ++b;
      }
      t /= 10;
      ++k;
    }
    if (k % 2 == 1) {
      int x = (int) Math.pow(10, k);
      int y = 0;
      for (int i = 0; i < k >> 1; ++i) {
        y = y * 10 + 1;
      }
      return x + y;
    }
    if (a == b) {
      return n;
    }
    return closestFair(n + 1);
  }
}
class Solution {
public:
  int closestFair(int n) {
    int a = 0, b = 0;
    int t = n, k = 0;
    while (t) {
      if ((t % 10) & 1) {
        ++a;
      } else {
        ++b;
      }
      ++k;
      t /= 10;
    }
    if (a == b) {
      return n;
    }
    if (k % 2 == 1) {
      int x = pow(10, k);
      int y = 0;
      for (int i = 0; i < k >> 1; ++i) {
        y = y * 10 + 1;
      }
      return x + y;
    }
    return closestFair(n + 1);
  }
};
func closestFair(n int) int {
  a, b := 0, 0
  t, k := n, 0
  for t > 0 {
    if (t%10)%2 == 1 {
      a++
    } else {
      b++
    }
    k++
    t /= 10
  }
  if a == b {
    return n
  }
  if k%2 == 1 {
    x := int(math.Pow(10, float64(k)))
    y := 0
    for i := 0; i < k>>1; i++ {
      y = y*10 + 1
    }
    return x + y
  }
  return closestFair(n + 1)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文