Java程序练习-计算2的N次方

  计算2的N次方
时间限制: 1000ms内存限制: 65536kB
描述
任意给定一个正整数N(N<=100),计算2的N次方的值。
输入
输入只有一个正整数N。
输出
输出2的N次方的值。
样例输入
5
样例输出
32
参考代码
import java.util.*;
public class Main {
	public final static int SIZE = 30;
	public static void main(String[] args) throws Exception {
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		int res[] = new int[SIZE + 1];
		int i;
		for(i = 0;i < SIZE;++ i){
			res[i] = 0;
		}
		res[0] = 1;
		while(n > 0){
			for(i = 0;i < SIZE;++ i){
				res[i] *= 2;
			}
			for(i = 0;i < SIZE;++ i){
				if(res[i] > 9){
					res[i + 1] += res[i] / 10;
					res[i] %= 10;
				}
			}
			n --;
		}
		boolean bl = false;
		StringBuffer bf = new StringBuffer();
		for(i = SIZE;i >= 0;-- i){
			if(res[i] != 0 || bl){
				bf.append(res[i]);
				bl = true;
			}
		}
		System.out.println(bf);
	}
} 

根据高位低位改进的代码:

/*
 * Title  :power 2
 * From   :http://blog.csdn.net/binfeihan/article/details/6858655
 * Time   :2011-10-11 21:10PM 
 * Author :Eric Zhou,binfeihan
 * Email  :binfeihan@126.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
	public static void main(String[] args) throws IOException{
		BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(cin.readLine().trim());
		System.out.println(my_power_2(n));
		//System.out.println(Long.MAX_VALUE);
		//System.out.println(Long.MIN_VALUE);
	}
	public static StringBuffer my_power_2(int N){
		StringBuffer v = new StringBuffer("");
		long num[] = new long[2];
	    num[1] = 1;
	    if(N > 62){
	       num[0] = 1;
	       num[0] = num[0]<<(N - 62);
	       num[1] = num[1]<<62;
	       String s = String.valueOf(num[1]);
	       int size = 30,i = 0,j = 0;
	       long n[] = new long[size + 1];
	       //System.out.println(num[0]+" "+s);
	       for(i = s.length() - 1;i >= 0;-- i){
	    	   n[j ++] = (long) (num[0] * (s.charAt(i) - '0'));
	    	   //System.out.println(n[j - 1]);
	       }
	       for(i = 0;i < size;++ i){
	    	   while(n[i] > 9){
	    		   n[i + 1] += n[i] / 10;
	    		   n[i] %= 10;
	    	   }
	       }
	       boolean bl = false;
	       for(i = size;i >= 0;-- i){
	    	   if(n[i] != 0 || bl){
	    		   v.append(n[i]);
	    		   bl = true;
	    	   }
	       }
	    }else{
	       num[1] = num[1] << N;
	       v.append(String.valueOf(num[1]));
	    }   
	    return v;
	}
}

 

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值