Problem #2 Write a method named palindromeAddNumber in Java that accepts an inte
ID: 3878223 • Letter: P
Question
Problem #2 Write a method named palindromeAddNumber in Java that accepts an integer parameter and repeatedly adds the integer to the reversal of itself (the integer constructed by reversing the order of the digits) until the result is a palindrome (an integer that is the same when the order of its digits is reversed). Your method should print a single line of output containing the number of adds that were needed, followed by a space, followed by the palindrome that was computed. For example, the call of palindromeAddNumber(195); should print: 4 9339 because: 195 (initial number) + 591 add #1 786 + 687 add #2 1473 + 3741 add #3 5214 + 4125 add #4 9339 (resulting palindrome)
Explanation / Answer
class Main {
// method that takes integer as a parameter
public static void palindromeAddNumber(int n)
{
// reversed is a variable that stores the reverse of the number
int reversed=0, temp=n, r;
int count = 0;
// looping till we get a palindrome
while(reversed != temp)
{
reversed = 0;
n = temp;
// getting reverse of given number
while(n>0)
{
r=n%10;
reversed=(reversed*10)+r;
n=n/10;
}
// checking if reverse is same
if(reversed == temp)
{
System.out.println(count +" " + reversed);
}
// if not, trying with adding both the numbers
else
{
count = count + 1;
temp = reversed + temp;
}
}
}
public static void main(String[] args) {
palindromeAddNumber(195);
}
}
// Output: 4 9339
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.