2的N次方
總提交:1735 測試通過:850
描述
編程精確計算2的N次方。(N是介於100和1000之間的整數)。
輸入
正整數N (100≤N≤1000)
輸出
2的N次方
樣例輸入
200
樣例輸出
1606938044258990275541962092341162602522202993782792835301376
題目來源
NUPT
private static final int MAX=2000;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
fun1(n);
}
方法1:傳統方法,用數組模擬計算和進位。對於每次乘2,從最後一位開始,乘2,如果有進位,那麼此位的值爲乘積%10;前面的數,乘2後,判斷後面是否有進位,有進位那麼加1,再判斷此位是否有進位。 從後位遍歷到第一位,即可以得到最終結果。
private static void fun(int n) {
int[] arr=new int[MAX];
int index=0;
arr[0]=2;
for(int i=1;i<n;i++){
int jinwei=0;
for(int j=0;j<=index;j++){
int temp=1;
if(j==0){
temp=arr[j]*2;
if(temp>=10){
jinwei=1;
}
}else{
temp=arr[j]*2;
if(jinwei==1){
temp+=1;
}
if(temp>=10){
jinwei=1;
}else{
jinwei=0;
}
}
arr[j]=temp%10;
}
if(jinwei==1){
index++;
arr[index]=1;
}
}
for(int i=index;i>=0;i--){
System.out.print(arr[i]);
}
}
方法二:利用JAVA大數處理(BigInteger,BigDecimal)
在用C或者C++處理大數時感覺非常麻煩,但是在JAVA中有兩個類BigInteger和BigDecimal分別表示大整數類和大浮點數類,至於兩個類的對象能表示最大範圍不清楚,理論上能夠表示無線大的數,只要計算機內存足夠大。這兩個類都在java.math.*包中,因此每次必須在開頭處引用該包。
private static void fun1(int n) {
BigInteger a=BigInteger.valueOf(1);
BigInteger b=BigInteger.valueOf(2);
for(int i=0;i<n;i++){
a=a.multiply(b);
}
System.out.println(a);
}
對於方法一:代碼可做簡化爲:
private static void fun(int n) {
int[] arr=new int[MAX];
int index=0;
arr[0]=2;
for(int i=1;i<n;i++){
int jinwei=0;
for(int j=0;j<=index;j++){
int temp=0;
/*if(j==0){
temp=arr[j]*2;
if(temp>=10){
jinwei=1;
}
}else{
temp=arr[j]*2;
if(jinwei==1){
temp+=1;
}
if(temp>=10){
jinwei=1;
}else{
jinwei=0;
}
}*/
//以上代碼可以化簡 因爲在j=0時,jinwei=0
temp=arr[j]*2+jinwei;
if(temp>=10){
jinwei=1;
}else{
jinwei=0;
}
arr[j]=temp%10;
}
if(jinwei==1){
index++;
arr[index]=1;
}
}
for(int i=index;i>=0;i--){
System.out.print(arr[i]);
}
}