javascript – 确定整数是否可以表示为回文总和

我在接受采访时被问到这个问题:

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 equals 29+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 举报,一经查实,本站将立刻删除。

相关推荐


kindeditor4.x代码高亮功能默认使用的是prettify插件,prettify是Google提供的一款源代码语法高亮着色器,它提供一种简单的形式来着色HTML页面上的程序代码,实现方式如下: 首先在编辑器里面插入javascript代码: 确定后会在编辑器插入这样的代码: <pre
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代码高亮,因为SyntaxHighlighter的应用非常广泛,所以将kindeditor默认的prettify替换为SyntaxHighlighter代码高亮插件 上一篇“让kindeditor显示高亮代码”中已经
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)
原生JS实现别踩白块小游戏(一)