2的1000次各位数的和

本文介绍了一种使用数组存储大整数的方法来计算2的1000次方,并实现了一种算法用于求解最终结果中所有位数的总和。该算法的时间复杂度为O(n^2),空间复杂度为Theta(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理:

2的1000次方用基本数据结构无法储存,所以想到用数组储存(链表也可以),我的思路:用足够大的数组(这里是1000),每个数组储存4个位数(也就是相当于10000进制大于9999时前面的数组加1)代码如下:

package 程序测试专用;


public class BinaryPlus {
<span style="white-space:pre">	</span>private final static int POW = 100000;
<span style="white-space:pre">	</span>private static int[] a = new int[POW ];
<span style="white-space:pre">	</span>public static void store(){
<span style="white-space:pre">		</span>a[a.length-1] = 1;


<span style="white-space:pre">		</span>for(int i=1;i<=POW ;i++){
<span style="white-space:pre">			</span>for(int j=a.length-1;j>=0;j--){
<span style="white-space:pre">				</span>a[j] *= 2;
<span style="white-space:pre">				</span>if(j+1<=a.length-1&&a[j+1]>9999){
<span style="white-space:pre">					</span>//System.out.println(a[a.length-1]);
<span style="white-space:pre">					</span>a[j] += 1;
<span style="white-space:pre">					</span>a[j+1] -= 10000; 
<span style="white-space:pre">				</span>}
<span style="white-space:pre">				</span>//System.out.println(a[j]);
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public static int count(){
<span style="white-space:pre">		</span>int count = 0;
<span style="white-space:pre">		</span>for(int i=0;i<=a.length-1;i++){
<span style="white-space:pre">			</span>while(a[i]!=0){
<span style="white-space:pre">				</span>count += a[i]%10;
<span style="white-space:pre">				</span>a[i] /= 10;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return count;
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public static void main(String[] args){
<span style="white-space:pre">		</span>store();<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>/*for(int i=0;i<a.length;i++){
<span style="white-space:pre">			</span>if(a[i]!=0)
<span style="white-space:pre">			</span>System.out.println(a[i]);
<span style="white-space:pre">		</span>}*/
<span style="white-space:pre">		</span>System.out.println(count());
<span style="white-space:pre">	</span>}
}

但是当计算出的十进制大于4位时(列入计算2的15次方,结果为29位应为26位),我调试时发现进位发生在乘之前,导致高位进位后乘以2(其实应该是先乘之后再进位)

该算法的时间复杂度Tn = O(n^2) 空间复杂度Sn = Theta(n)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值