加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

大数加法

发布时间:2020-12-14 02:54:28 所属栏目:大数据 来源:网络整理
导读:好久没写C程序,吃力啊,菜成狗。。。http://www.smartoj.com/p/1001 python四行代码java10多行,C居然写了70+,无聊ing。。。注意0000016+0000000000000003=19; ?0+0=0;就是说忽略前导0的时候得考虑两个数都是0的情况。 其他的是个人都写得出。 import java

好久没写C程序,吃力啊,菜成狗。。。http://www.smartoj.com/p/1001

python四行代码java10多行,C居然写了70+,无聊ing。。。注意0000016+0000000000000003=19; ?0+0=0;就是说忽略前导0的时候得考虑两个数都是0的情况。

其他的是个人都写得出。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		while(scan.hasNext()){
			BigInteger bi = new BigInteger(scan.next());
			BigInteger bi2 = new BigInteger(scan.next());
			System.out.println(bi.add(bi2));
		}
	}
}


#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;

char a[1005],b[1005];

void addAndOutput(char* longer,char* shorter){
    /*init*/
    int longer_length = strlen(longer);
    int shorter_length = strlen(shorter);
    int p = longer_length-1;
    int q = shorter_length-1;

    /*实现加法*/
    int increase = 0,headFlag = 0;
    while(q>=0){
        if((longer[p]+shorter[q]-2*'0'+increase) >= 10){
            longer[p] = (longer[p]+shorter[q]-2*'0'+increase)%10 + '0';
            increase = 1;
        }
        else{
            longer[p] = (longer[p]+shorter[q]-2*'0'+increase)%10 + '0';
            increase = 0;
        }
        p--,q--;
    }
    /*若还有进位处理*/
    if(increase){//有进位
        if(p>=0){//未到头
            while(p>=0 && increase!=0){
                if(longer[p]-'0'+1>=10){
                    longer[p] = (longer[p]-'0'+1)%10 + '0';
                    increase = 1;
                }else{
                    longer[p] = longer[p]+1;
                    increase = 0;
                }
                p--;
            }
            if(increase==1){
                putchar('1');
                headFlag = 1;
            }
        }else{//已经到头
            putchar('1');
            headFlag = 1;
        }
    }

    /*去前导0*/
    int k=0,zeroFlag=1;
    if(!headFlag){
        for(k = 0; k < longer_length; k++)
            if(longer[k] != '0'){
                    zeroFlag = 0;
                    break;
            }
    }
    if(zeroFlag) printf("0");
    else for(int i = k; i < longer_length; ++i) printf("%c",longer[i]);
    puts("");
}

int main(){
    while(~scanf("%s%s",a,b)){
        if(strlen(a) < strlen(b)) addAndOutput(b,a);
        else addAndOutput(a,b);
        memset(a,sizeof(a));
        memset(b,sizeof(b));
    }
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读