Leetcode

Next Greater Numerically Balanced Number

  • Time:O(100000\log 100000)
  • Space:O(1)

C++

class Solution {
 public:
  int nextBeautifulNumber(int n) {
    while (!isBalance(++n))
      ;
    return n;
  }

 private:
  bool isBalance(int num) {
    vector<int> count(10);
    while (num) {
      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;
  }
};

JAVA

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;
  }
}

Python

class Solution:
  def nextBeautifulNumber(self, n: int) -> int:
    def isBalance(num: int) -> bool:
      count = [0] * 10
      while num:
        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