Palindrome Number of 1079 Delay in PAT Class B
Problem Solution: For a given string, judge whether it can get palindrome number by adding it with its reverse string. Output the result of adding each step. Stop judging when it exceeds 10 steps. Output "Not found in 10 iterations." If palindrome number is obtained within 10 steps, output "? It is a palindromic number. "(It is pointed out here that 0 and digits are palindromic numbers themselves, and there is no need to judge the output.)
Core: Because this positive integer does not exceed 1000 bits, can not be converted to integer or long type, because this number has exceeded the data range of long type, so here we use strings to realize the addition of large integers. Because the two digits are the same, the sum is relatively simple, if the digits are different, this consideration will be much more. . (See https://blog.csdn.net/CSDN_Lrcx/article/details/100143856 for details if you want to add up large integers of different digits. If you look at it carefully, you'll get something.)
package lowlevel; import java.io.BufferedReader; import java.io.InputStreamReader; /* The sum of large integers */ public class I079 { public static void main(String[] args)throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String A=br.readLine(); br.close(); int count=0;//Record the number of palindromes counted, which ends when more than 10. I079 pat=new I079(); // System.out.println(pat.sum(A)); while (!pat.palin(A)&&count<10){//If the sum is palindrome, or more than 10 steps, exit the loop String str=""; char[] c=A.toCharArray(); for(int i=c.length-1;i>=0;i--){ str+=c[i]; } String B=A; //Record the data of A before, easy to output A=pat.sum(A); count++; System.out.println(B+" + "+str+" = "+A); } if(count==10){ System.out.println("Not found in 10 iterations."); }else{ System.out.println(A+" is a palindromic number."); } } //A Method of Judging whether a Number is Palindrome Number public Boolean palin(String num){ char[] c=num.toCharArray(); Boolean flag=true; for(int i=0;i<c.length;i++){ if(c[i]!=c[c.length-i-1]){ flag=false; break; } } if(flag==true){ return true; }else{ return false; } } //This is the core of the method of adding positive numbers of two strings. public String sum(String a){ char[] c=a.toCharArray(); String str=""; int carry=0; for(int i=c.length-1;i>=0;i--){ int result=c[i]+c[c.length-i-1]-48-48+carry; if(result>=10){ result=result-10; carry=1; }else{ carry=0; } str+=result; } if(carry==1){ str=str+1; } c=str.toCharArray(); str=""; for(int i=c.length-1;i>=0;i--){ str+=c[i]; } return str; } }