1. 程式人生 > >HDU——5920 Ugly Problem (java大數加思維)

HDU——5920 Ugly Problem (java大數加思維)

Everyone hates ugly problems. 

You are given a positive integer. You must represent that number by sum of palindromic numbers. 

A palindromic number is a positive integer such that if you write out that integer as a string in decimal without leading zeros, the string is an palindrome. For example, 1 is a palindromic number and 10 is not.

Input

In the first line of input, there is an integer T denoting the number of test cases.

For each test case, there is only one line describing the given integer s (1≤s≤1010001≤s≤101000).

Output

For each test case, output “Case #x:” on the first line where x is the number of that test case starting from 1. Then output the number of palindromic numbers you used, n, on one line. n must be no more than 50. en output n lines, each containing one of your palindromic numbers. Their sum must be exactly s.

Sample Input

2
18
1000000000000

Sample Output

Case #1:
2
9
9
Case #2:
2
999999999999
1   

Hint

9 + 9 = 18
999999999999 + 1 = 1000000000000

題意:把一個大數拆成幾個迴文數的和,迴文數的數量小於等於50個。

題解:運用java大數來寫,看程式碼,程式碼裡有解釋

import java.util.*;
import java.math.*;
public class Main {
	static Scanner cin = new Scanner(System.in);
	public static void main(String[] args){
		int t;
		t = cin.nextInt();
		BigInteger a = BigInteger.valueOf(0),ten=BigInteger.valueOf(20);//20是因為後面減1,如果不是20就死迴圈了,準確來說第一位不能是1
		BigInteger tmpa,tmpa1;
		String s,tmps,tmps1,tmps2;
		String ss[] = new String[55];//用來存每一個迴文數
		int xx = 0;
		for (int i = 1; i <= t;i++) {
			xx=0;
			a = cin.nextBigInteger();//假設a為59634102長度為偶數,奇數反轉時候再減1就好了,下面解釋
			System.out.printf("Case #%d:\n",i);
			while(a.compareTo(ten)>=1) {
				s = a.toString();
				int len = s.length();
				tmps = s.substring(0, (len+1)/2); //5963
				tmpa = new BigInteger(tmps);
				tmpa = tmpa.subtract(BigInteger.valueOf(1));//5962
				tmps1=tmpa.toString();
				if((len&1)!=1) {//為偶數
					StringBuffer sb = new StringBuffer(tmps1);
					sb.reverse();//2695
					tmps2 = sb.toString();
					tmps=tmps1+tmps2;
					tmpa1 = new BigInteger(tmps);
					a = a.subtract(tmpa1);
					ss[xx++]=tmps;//59622695  這裡只解釋第一步迴圈
				}
				else {
					int len1=tmps1.length();
	                tmps2="";
	                for(int j = len1-2; j >= 0;j--){//再減一
	                    tmps2+=tmps1.charAt(j);
	                }
	                tmps=tmps1+tmps2;
	                tmpa1=new BigInteger(tmps);
	                a=a.subtract(tmpa1);
	                ss[xx++]=tmps;
				}
			}
			int ans = a.intValue();
			if(ans>=10) {
				ss[xx++]="9";
				ss[xx++]=String.valueOf(ans-9);
			}
			else {
				ss[xx++]=String.valueOf(ans);
			}
			System.out.println(xx);
			for (int r = 0; r < xx;r++) {
				System.out.println(ss[r]);
			}
		}
	}
}