🌕🌗🌑🌑🌑
# 題目連結
- 題目連結
- Online Judge
- uDebug
# 題目說明
Time limit: 3.000 seconds
# 題目
The “reverse and add” method is simple: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure.
In this particular case the palindrome ‘9339’ appeared after the 4th addition. This method leads to palindromes in a few step for almost all of the integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It is not proven though, that there is no such a palindrome.
You must write a program that give the resulting palindrome and the number of iterations (additions) to compute the palindrome.
You might assume that all tests data on this problem:
- will have an answer ,
- will be computable with less than 1000 iterations (additions),
- will yield a palindrome that is not greater than 4,294,967,295.
# Input
The first line will have a number N (0 < N ≤ 100)
with the number of test cases, the next N lines will have a number P to compute its palindrome.
# Output
For each of the N tests you will have to write a line with the following data : minimum number of iterations (a and the resulting palindrome itself separated by one space.
# Sample Input
3
195
265
750
# Sample Output
4 9339
5 45254
3 6666
# 解題技巧
- 計算時 int 會不夠用
# Solution
import java.util.*; | |
public class Main { | |
public static void main(String args[]) { | |
Scanner sc = new Scanner(System.in); | |
int line = sc.nextInt(); | |
for (int i = 0; i < line; i++) { | |
String str = sc.next();; | |
int count = 0; | |
while (true) { | |
StringBuffer sb = new StringBuffer(str); | |
String restr = sb.reverse().toString(); | |
long tmp = Math.abs(Long.parseLong(str) + Long.parseLong(restr)); | |
str = Long.toString(tmp); | |
boolean isPalindrome = true; | |
for(int j = 0; j < str.length() / 2; j++){ | |
if(str.charAt(j) != str.charAt(str.length() - 1 -j)){ | |
isPalindrome = false; | |
} | |
} | |
count++; | |
if(isPalindrome){ | |
break; | |
} | |
} | |
System.out.println(count + " " + str); | |
} | |
sc.close(); | |
} | |
} |
單字
** **
!! !!
片語 & 搭配詞
!! !!