又是今天的面試題,上級操做,linux環境文本編輯器下寫代碼; java
題目大概就是說:給一個數,先求出這個數的階層。在這個階層的基礎上把各個位相加好比:階層結果=56 linux
相加 5+6=11;要求給出的是輸入100 輸出相加的結果; 面試
import java.math.BigInteger; /* * 求一個數的階層,獲得的數字每一個位相加,輸出最終相加的數字; */ public class NumberCount { public static void main(String[] args) { NumberCount cu = new NumberCount(); long star1 = System.currentTimeMillis(); int ree = cu.count(new BigInteger(1000+"")); System.out.println("ree"+ree+"用時:"+(System.currentTimeMillis()-star1)); long star2 = System.currentTimeMillis(); BigInteger amount = cu.Calculate(BigInteger.valueOf(1000)); System.out.println(amount); int [] a = new int[500]; int real =0; int result =cu.countInt(amount, 0, a,real); System.out.println(); System.out.println(result+"用時:"+(System.currentTimeMillis()-star2)); } private BigInteger Calculate(BigInteger num) { //System.out.println(num); if(num.intValue() ==1) { return BigInteger.ONE; } if(num.intValue() > 1) { return num.multiply(Calculate(BigInteger.valueOf((num.subtract(BigInteger.valueOf(1))).longValue()))); } return BigInteger.ONE; } public int count(BigInteger c) { BigInteger re = Calculate(c); System.out.println(re); String str = re.toString(); char[] ch = str.toCharArray(); int result = 0; for(int i=0; i<ch.length; i++) { result += Integer.parseInt(ch[i]+""); } return result; } /** * 求模的方式,效率彷佛沒字符串方式高 * @param num * @param index * @param a * @return */ public int countInt(BigInteger num,int index,int[] a,int result) { //int leg = index+1; //if(leg==a.length) { //數組自動加長 // a = Arrays.copyOf(a, leg+10); //} //求模,獲得個位數 BigInteger bit = num.mod(BigInteger.valueOf(10)); //把個位數放入數組 //a[index]= bit.intValue(); //把個位數直接跟結果相加 result +=bit.intValue(); BigInteger newpNum = num.subtract(bit); //除去個位 BigInteger newNum = newpNum.divide(BigInteger.valueOf(10)); if(newNum.compareTo(BigInteger.valueOf(10))<0) { //a[++index] = newNum.intValue(); result +=newNum.intValue(); return result; } return countInt(newNum,index+1,a,result); } }
public class BigInteger extends Number implements Comparable<BigInteger> {