这次比赛不难, 就是把一个4个数字的电子屏倒过来,
就成这样:
问题是我们需要多少块(每块倒着可以用)
首先, 写一个函数, 用于返回一个数字是否可以倒过来, 像7这种倒过来没有意义的就可以返回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; } }
给定一个4位数, 计算倒过来的数字, 如果倒过来无意义, 返回FALSE.
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); }
然后就是从0到9999, 每次检查是否已经出现了, 否则统计加1, 然后把倒过来的数字也标记上了.
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);
这样就能打印出正确的答案了, 希望能获奖!
英文: [Answer] Mathematics × Programming Competition #8 – Four Digit Calculator
强烈推荐
- 英国代购-畅购英伦
- TopCashBack 返现 (英国购物必备, 积少成多, 我2年来一共得了3000多英镑)
- Quidco 返现 (也是很不错的英国返现网站, 返现率高)
- 注册就送10美元, 免费使用2个月的 DigitalOcean 云主机(性价比超高, 每月只需5美元)
- 注册就送10美元, 免费使用4个月的 Vultr 云主机(性价比超高, 每月只需2.5美元)
- 注册就送10美元, 免费使用2个月的 阿里 云主机(性价比超高, 每月只需4.5美元)
- 注册就送20美元, 免费使用4个月的 Linode 云主机(性价比超高, 每月只需5美元) (折扣码: PodCastInit2022)
- PlusNet 英国光纤(超快, 超划算! 用户名 doctorlai)
- 刷了美国运通信用卡一年得到的积分 换了 485英镑
- 注册就送50英镑 – 英国最便宜最划算的电气提供商
- 能把比特币莱特币变现的银行卡! 不需要手续费就可以把虚拟货币法币兑换
微信公众号: 小赖子的英国生活和资讯 JustYYUK