Given a four digit calculator, if you rotate it by 180 degree, you may get another ‘valid’ number. For example,
0159 becomes 6510 if rotated 180 degree. The ‘1’ is still valid even it is on the other side.
The question comes: how many numbers are required to represent from 0000 to 9999?
First, we need a function to tell if a digit can be rotated… if not, e.g. like 7, we need to return false.
1 2 3 4 5 6 7 8 9 10 11 12 | function getRevDig(x) { switch (x) { case 0: return 0; case 1: return 1; case 2: return 2; case 5: return 5; case 6: return 9; case 8: return 8; case 9: return 6; default: return false; } } |
function getRevDig(x) { switch (x) { case 0: return 0; case 1: return 1; case 2: return 2; case 5: return 5; case 6: return 9; case 8: return 8; case 9: return 6; default: return false; } }
Now, given a four digit number, we need to return its rotated version, to get each digit, you can use module operator and division.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function getRev(x) { var a = x % 10; a = getRevDig(a); if (a === false) return false; var b = Math.floor(x / 10) % 10; b = getRevDig(b); if (b === false) return false; var c = Math.floor(x / 100) % 10; c = getRevDig(c); if (c === false) return false; var d = Math.floor(x / 1000); d = getRevDig(d); if (d === false) return false; return (a * 1000 + b * 100 + c * 10 + d); } |
function getRev(x) { var a = x % 10; a = getRevDig(a); if (a === false) return false; var b = Math.floor(x / 10) % 10; b = getRevDig(b); if (b === false) return false; var c = Math.floor(x / 100) % 10; c = getRevDig(c); if (c === false) return false; var d = Math.floor(x / 1000); d = getRevDig(d); if (d === false) return false; return (a * 1000 + b * 100 + c * 10 + d); }
The rest is straightforward, just to check and mark the number and its flipped version in a dictionary-like data structure (or array).
1 2 3 4 5 6 7 8 9 10 11 12 13 | var total = 0; var a = {}; for (var i = 0; i <= 9999; ++i) { if (!(i in a)) { total ++; a[i] = 1; var x = getRev(i); if (x !== false) { a[x] = 1; } } } console.log(total); |
var total = 0; var a = {}; for (var i = 0; i <= 9999; ++i) { if (!(i in a)) { total ++; a[i] = 1; var x = getRev(i); if (x !== false) { a[x] = 1; } } } console.log(total);
That should give you the correct answer – 8824.
You may also like: [答案] 数学 × 程式编写比赛 (第八回) – 4位数的电子显示器
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: The Simple Risk Register for Project Management
Next Post: SteemSQL Tutorial - Finding Inactive Steemians that You Follow