Skip to content

Commit c497485

Browse files
authored
Merge pull request #242 from jeantimex/rotated-digits
Rotated Digits
2 parents 26a27c7 + d24d15e commit c497485

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
109109
- [Sort Characters By Frequency](src/string/sort-characters-by-frequency.js)
110110
- [Binary Watch](src/string/binary-watch.js)
111111
- [Magical String](src/string/magic-string.js)
112+
- [Rotated Digits](src/string/rotated-digits.js)
112113

113114
### Sorting
114115

src/string/rotated-digits.js

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* Rotated Digits
3+
*
4+
* X is a good number if after rotating each digit individually by 180 degrees,
5+
* we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.
6+
*
7+
* A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5
8+
* rotate to * each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any
9+
* other number and become * invalid.
10+
*
11+
* Now given a positive number N, how many numbers X from 1 to N are good?
12+
*
13+
* Example:
14+
* Input: 10
15+
* Output: 4
16+
*
17+
* Explanation:
18+
* There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
19+
*
20+
* Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
21+
*
22+
* Note:
23+
*
24+
* N will be in range [1, 10000].
25+
*/
26+
27+
/**
28+
* @param {number} N
29+
* @return {number}
30+
*/
31+
const rotatedDigits = N => {
32+
// Count how many n in [1, N] are good.
33+
let ans = 0;
34+
35+
for (let n = 1; n <= N; ++n) {
36+
if (isGood(n, false)) ans++;
37+
}
38+
39+
return ans;
40+
};
41+
42+
// Return true if n is good.
43+
// The flag is true iff we have an occurrence of 2, 5, 6, 9.
44+
const isGood = (n, flag) => {
45+
if (n == 0) return flag;
46+
47+
const d = n % 10;
48+
49+
if (d == 3 || d == 4 || d == 7) {
50+
return false;
51+
}
52+
53+
if (d == 0 || d == 1 || d == 8) {
54+
return isGood(Math.floor(n / 10), flag);
55+
}
56+
57+
return isGood(Math.floor(n / 10), true);
58+
};
59+
60+
export { rotatedDigits };

0 commit comments

Comments
 (0)