Numerically Balanced: brute-force, still fast

Nothing really special about problem solved 938th, as a matter of fact, this one got lots of negative votes because honestly, it isn't that cool indeed.
Create a function to check whether a number is numerically balanced. Some simple calculation, and you can do it in constant time (like O(10)...). Then, keep going from n+1 to oo, until you find a balanced number. Return it. Pretty boring. Code is below fellas, cheers, ACC.


2048. Next Greater Numerically Balanced Number
Medium

An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.

Given an integer n, return the smallest numerically balanced number strictly greater than n.

 

Example 1:

Input: n = 1
Output: 22
Explanation: 
22 is numerically balanced since:
- The digit 2 occurs 2 times. 
It is also the smallest numerically balanced number strictly greater than 1.

Example 2:

Input: n = 1000
Output: 1333
Explanation: 
1333 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times. 
It is also the smallest numerically balanced number strictly greater than 1000.
Note that 1022 cannot be the answer because 0 appeared more than 0 times.

Example 3:

Input: n = 3000
Output: 3133
Explanation: 
3133 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 3000.

 

Constraints:

  • 0 <= n <= 106


public int NextBeautifulNumber(int n)
{
    for (long i = n + 1; i < Int32.MaxValue; i++)
    {
        if (IsNumericallyBalanced(i)) return (int)i;
    }
    return -1;
}

public bool IsNumericallyBalanced(long n)
{
    int[] count = new int[10];

    while (n > 0)
    {
        int digit = (int)(n % 10);
        if (digit == 0) return false;
        count[digit]++;
        if (count[digit] > digit) return false;
        n /= 10;
    }

    for (int i = 0; i < 10; i++)
    {
        if (count[i] > 0 && count[i] != i) return false;
    }

    return true;
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval