package eecs.hm; public class M1 { /* Given a positive integer n, return the num
ID: 3808010 • Letter: P
Question
package eecs.hm;
public class M1
{
/*
Given a positive integer n, return the number of "palindro additions" needed
to make it a palindrome (i.e. reads the same left-to-right and right-to-left).
A "palindro addition" is the addition of the number to its inverse.
For example, if n = 159 then the first palindro addition yields 159+951=1110,
and the second palindro addition yields 1110+111=1221, which is a palindrome.
Hence, the palindro count of 159 is 2.
If n is already a palindrome then return zero, and if the number does not
become a palindrome after 10 palindro additions then return -1.
*/
public static int palindroCount(int n)
{
return -1; // delete me!
}
}
Explanation / Answer
M1.java
public class M1 {
public static void main(String[] args) {
System.out.println(palindroCount(159));
}
/*
Given a positive integer n, return the number of "palindro additions" needed
to make it a palindrome (i.e. reads the same left-to-right and right-to-left).
A "palindro addition" is the addition of the number to its inverse.
For example, if n = 159 then the first palindro addition yields 159+951=1110,
and the second palindro addition yields 1110+111=1221, which is a palindrome.
Hence, the palindro count of 159 is 2.
If n is already a palindrome then return zero, and if the number does not
become a palindrome after 10 palindro additions then return -1.
*/
public static int palindroCount(int n)
{
int count = 1;
int reverseNum = reverse(n);
int total = n;
if(total != reverseNum){
total = n + reverseNum;
reverseNum = reverse(total);
count++;
}
return count;
}
public static int reverse(int n)
{
int reversenum = 0;
while(n > 0){
int r = n % 10;
reversenum = reversenum * 10 + r;
n = n / 10;
}
return reversenum;
}
}
Output:
2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.