计算2的n次方(n大于等于0)
1private static String strDigit(int n) {//2的n次方
2 StringBuffer stringBuffer = new StringBuffer();
3 stringBuffer.append("1");
4 while (n-- > 0) {
5 //overflow表示是否有进位
6 int overflow = 0;
7 for (int length = stringBuffer.length(), i = length - 1; i >= 0; i--) {
8 int digit = stringBuffer.charAt(i) - '0';
9 digit = (digit << 1) + overflow;
10 overflow = digit / 10;
11 int mod = digit % 10;
12 stringBuffer.replace(i, i + 1, mod + "");
13 }
14 if (overflow != 0) {
15 stringBuffer.insert(0, overflow);
16 }
17 }
18 return stringBuffer.toString();
19}
解析:
如果使用int或long类型,很容易溢出,所以我们通过字符串来计算。代码比较简单,我们来列几组数据看一下运行的结果
1public static void main(String args[]) {
2 System.out.println("2的" + 0 + "次方等于" + strDigit(0));
3 System.out.println("2的" + 1 + "次方等于" + strDigit(1));
4 System.out.println("2的" + 5 + "次方等于" + strDigit(5));
5 System.out.println("2的" + 10 + "次方等于" + strDigit(10));
6 System.out.println("2的" + 64 + "次方等于" + strDigit(64));
7 System.out.println("2的" + 100 + "次方等于" + strDigit(100));
8 System.out.println("2的" + 1000 + "次方等于" + strDigit(1000));
9}
结果为
2的0次方等于1
2的1次方等于2
2的5次方等于32
2的10次方等于1024
2的64次方等于18446744073709551616
2的100次方等于1267650600228229401496703205376
2的1000次方等于10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376