Skip to content

2048. Next Greater Numerically Balanced Number 👎

  • Time: $O(100000\log 100000)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int nextBeautifulNumber(int n) {
    while (!isBalance(++n))
      ;
    return n;
  }

 private:
  bool isBalance(int num) {
    vector<int> count(10);
    while (num > 0) {
      if (num % 10 == 0)
        return false;
      ++count[num % 10];
      num /= 10;
    }
    for (int i = 1; i < 10; ++i)
      if (count[i] && count[i] != i)
        return false;
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int nextBeautifulNumber(int n) {
    while (!isBalance(++n))
      ;
    return n;
  }

  private boolean isBalance(int num) {
    int[] count = new int[10];
    while (num > 0) {
      if (num % 10 == 0)
        return false;
      ++count[num % 10];
      num /= 10;
    }
    for (int i = 1; i < 10; ++i)
      if (count[i] > 0 && count[i] != i)
        return false;
    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def nextBeautifulNumber(self, n: int) -> int:
    def isBalance(num: int) -> bool:
      count = [0] * 10
      while num > 0:
        if num % 10 == 0:
          return False
        count[num % 10] += 1
        num //= 10
      return all(c == i for i, c in enumerate(count) if c)

    n += 1
    while not isBalance(n):
      n += 1
    return n