Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  110] [ 1]  / answers: 1 / hits: 15641  / 5 Years ago, thu, february 14, 2019, 12:00:00

I was asked this question in an interview:



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.



but I couldn't think of any solution. How can this be done?


More From » algorithm

 Answers
14

In the stress and the hurry of an interview, I would have certainly found a dumb and naive solution.



pseudo code



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




[#52595] Sunday, February 10, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiej

Total Points: 294
Total Questions: 95
Total Answers: 97

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;