-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0248-strobogrammatic-number-iii.js
More file actions
65 lines (56 loc) · 1.65 KB
/
0248-strobogrammatic-number-iii.js
File metadata and controls
65 lines (56 loc) · 1.65 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 248. Strobogrammatic Number III
* https://leetcode.com/problems/strobogrammatic-number-iii/
* Difficulty: Hard
*
* Given two strings low and high that represent two integers low and high where low <= high,
* return the number of strobogrammatic numbers in the range [low, high].
*
* A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked
* at upside down).
*/
/**
* @param {string} low
* @param {string} high
* @return {number}
*/
var strobogrammaticInRange = function(low, high) {
const pairs = [
['0', '0'],
['1', '1'],
['6', '9'],
['8', '8'],
['9', '6']
];
function generateStrobogrammatic(length, isOuter) {
if (length === 0) return [''];
if (length === 1) return ['0', '1', '8'];
const result = [];
const subNumbers = generateStrobogrammatic(length - 2, false);
for (const [left, right] of pairs) {
for (const sub of subNumbers) {
if (isOuter && left === '0') continue;
result.push(left + sub + right);
}
}
return result;
}
function countInRange(num, lowVal, highVal) {
if (num.length < lowVal.length || num.length > highVal.length) return false;
if (num.length === lowVal.length && num < lowVal) return false;
if (num.length === highVal.length && num > highVal) return false;
return true;
}
let count = 0;
const lowLength = low.length;
const highLength = high.length;
for (let len = lowLength; len <= highLength; len++) {
const numbers = generateStrobogrammatic(len, true);
for (const num of numbers) {
if (countInRange(num, low, high)) {
count++;
}
}
}
return count;
};