确定一个整数是否可以表示为回文和

新手上路,请多包涵

我在一次采访中被问到这个问题:

如果一个整数可以表示为回文的总和(向后与向前相同),则该整数是 特殊 的。例如,22 和 121 都是特殊的,因为 22 等于 11+11 而 121 等于 29+92

给定一个整数数组,计算其中有多少元素是特殊的。

但我想不出任何解决办法。如何才能做到这一点?

原文由 The Coder 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 267
2 个回答

在面试的压力和匆忙中,我肯定会找到一个愚蠢而天真的解决方案。

伪代码

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");

原文由 Cid 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是一个相当天真的伪代码解决方案,用于确定数字是否“特殊”:

 Given an number N (assumed to be an integer)
Let I = Floor(N / 2)
Let J = Ceil(N / 2)
While (I > 0)
    If I is the reverse of J Then
        Return True
    End
    I <- I - 1
    J <- J + 1
End
Return False

一个快速的 JS 实现:

 function isSpecial(n) {
  for (var i = Math.floor(n / 2), j = Math.ceil(n / 2); i > 0; i--, j++) {
    console.info(`checking ${i} + ${j}`);
    if (i.toString().split('').reverse().join('') === j.toString())
      return true;
  }

  return false;
}

console.log(isSpecial(121));

我将把它留给你实现函数来计算数组中的特殊数字。这可以通过改进用于检查字符串反转的相当粗略的方法或可能通过更智能地跳过数字来提高效率。

原文由 p.s.w.g 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题