aboutsummaryrefslogtreecommitdiff
path: root/balanced_num.c
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /balanced_num.c
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'balanced_num.c')
-rw-r--r--balanced_num.c40
1 files changed, 40 insertions, 0 deletions
diff --git a/balanced_num.c b/balanced_num.c
new file mode 100644
index 0000000..c7154ed
--- /dev/null
+++ b/balanced_num.c
@@ -0,0 +1,40 @@
+// 2048. Next Greater Numerically Balanced Number
+#include "leetcode.h"
+
+/*
+ * an integer 'x' is numerically balanced if for every digit 'd' in the number
+ * 'x', there are exactly 'd' occurences of that digit in 'x'. given an integer
+ * 'n', return the smallest numerically balanced number strictly greater than
+ * 'n'
+ */
+
+bool is_balanced(int n) {
+ int *digit = calloc(10, sizeof(int));
+ while (n) {
+ int d = n % 10;
+ n /= 10;
+ digit[d]++;
+ if (!d || digit[d] > d)
+ return 0;
+ }
+ for (int i = 1; i < 10; i++)
+ if (digit[i] && digit[i] != i)
+ return 0;
+ return 1;
+}
+
+int nextBeautifulNumber(int n) {
+ n += 1;
+ while (1) {
+ if (is_balanced(n))
+ return n;
+ n++;
+ }
+ return -1;
+}
+
+int main() {
+ printf("%d\n", nextBeautifulNumber(1)); // expect: 22
+ printf("%d\n", nextBeautifulNumber(1000)); // expect: 1333
+ printf("%d\n", nextBeautifulNumber(3000)); // expect: 3133
+}