-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2417-closest-fair-integer.js
More file actions
45 lines (41 loc) · 1.06 KB
/
2417-closest-fair-integer.js
File metadata and controls
45 lines (41 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* 2417. Closest Fair Integer
* https://leetcode.com/problems/closest-fair-integer/
* Difficulty: Medium
*
* 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.
*/
/**
* @param {number} n
* @return {number}
*/
var closestFair = function(n) {
const digitCount = n.toString().length;
if (digitCount % 2 === 1) {
return smallestFairNumberWithLength(digitCount + 1);
}
return hasEqualEvenOddDigits(n) ? n : closestFair(n + 1);
function hasEqualEvenOddDigits(num) {
const counts = [0, 0];
while (num > 0) {
counts[(num % 10) % 2]++;
num = Math.floor(num / 10);
}
return counts[0] === counts[1];
}
function smallestFairNumberWithLength(length) {
let result = '1';
for (let i = 1; i <= length / 2; i++) {
result += '0';
}
for (let i = length / 2 + 1; i < length; i++) {
result += '1';
}
return parseInt(result);
}
};