Ugly Problem 大数减法
题意:让我们把原序列拆分为50个以下的回文序列(回文序列相加等于原序列)
思路:找出中间位置,每次枚举的时候,右边-1,然后左边等于右边倒过来即可
1 import java.util.*; 2 import java.math.*; 3 public class Main { 4 static Scanner cin = new Scanner(System.in); 5 public static void main(String[] args){ 6 int t; 7 t = cin.nextInt(); 8 BigInteger a = BigInteger.valueOf(0),ten=BigInteger.valueOf(20);//20是因为后面减1,如果不是20就死循环了,准确来说第一位不能是1 9 BigInteger tmpa,tmpa1; 10 String s,tmps,tmps1,tmps2; 11 String ss[] = new String[55];//用来存每一个回文数 12 int xx = 0; 13 for (int i = 1; i <= t;i++) { 14 xx=0; 15 a = cin.nextBigInteger();//假设a为59634102长度为偶数,奇数反转时候再减1就好了,下面解释 16 System.out.printf("Case #%d:\n",i); 17 while(a.compareTo(ten)>=1) { 18 s = a.toString(); 19 int len = s.length(); 20 tmps = s.substring(0, (len+1)/2); //5963 21 tmpa = new BigInteger(tmps); 22 tmpa = tmpa.subtract(BigInteger.valueOf(1));//5962 23 tmps1=tmpa.toString(); 24 if((len&1)!=1) {//为偶数 25 StringBuffer sb = new StringBuffer(tmps1); 26 sb.reverse();//2695 27 tmps2 = sb.toString(); 28 tmps=tmps1+tmps2; 29 tmpa1 = new BigInteger(tmps); 30 a = a.subtract(tmpa1); 31 ss[xx++]=tmps;//59622695 这里只解释第一步循环 32 } 33 else { 34 int len1=tmps1.length(); 35 tmps2=""; 36 for(int j = len1-2; j >= 0;j--){//再减一 37 tmps2+=tmps1.charAt(j); 38 } 39 tmps=tmps1+tmps2; 40 tmpa1=new BigInteger(tmps); 41 a=a.subtract(tmpa1); 42 ss[xx++]=tmps; 43 } 44 } 45 int ans = a.intValue(); 46 if(ans>=10) { 47 ss[xx++]="9"; 48 ss[xx++]=String.valueOf(ans-9); 49 } 50 else { 51 ss[xx++]=String.valueOf(ans); 52 } 53 System.out.println(xx); 54 for (int r = 0; r < xx;r++) { 55 System.out.println(ss[r]); 56 } 57 } 58 } 59 }