我在接受采访时被问到这个问题:
An integer is special if it can be expressed as a sum that’s a palindrome (the same backwards as forwards). For example,22 and 121 are both special,because 22 equals
11+11
and 121 equals29+92
.Given an array of integers,count how many of its elements are special.
但我想不出任何解决方案.如何才能做到这一点?
解决方法
在面试的压力和匆忙中,我肯定会找到一个愚蠢而天真的解决方案.
伪代码
loop that array containing the numbers Looping from nb = 0 to (*the number to test* / 2) convert nb to string and reverse the order of that string (ie : if you get "29",transform it to "92") convert back the string to a nb2 if (nb + nb2 == *the number to test*) this number is special. Store it in the result array end loop end loop print the result array
function IsNumberSpecial(input) { for (let nb1 = 0; nb1 <= (input / 2); ++nb1) { let nb2 = parseInt(("" + nb1).split("").reverse().join("")); // get the reverse number if (nb2 + nb1 == input) { console.log(nb1 + " + " + nb2 + " = " + input); return (true); } } return (false); } let arr = [22,121,42]; let len = arr.length; let result = 0; for (let i = 0; i < len; ++i) { if (IsNumberSpecial(arr[i])) ++result; } console.log(result + " number" + ((result > 1) ? "s" : "") + " found");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。