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

大数相加,分别用C++和Java实现

发布时间:2020-12-14 03:31:47 所属栏目:大数据 来源:网络整理
导读:大家在A题的时候,大数相加是很常见的,都知道用字符串来做,但是实现起来可能有一些困难,接下来我就给大家讲讲我的做法 首先,用C++来做; #includeiostream #includecstring using namespace std; int main() { char a[100],b[100]; ? ? ?//用两个字符串来

大家在A题的时候,大数相加是很常见的,都知道用字符串来做,但是实现起来可能有一些困难,接下来我就给大家讲讲我的做法

首先,用C++来做;

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char a[100],b[100]; ? ? ?//用两个字符串来保存我们要输入的两个大树;
int i,j,k,lenth1,lenth2,lentha,lenthb,c[1000]; ?//用一个int数组来保留每一位相加后的结果,
cin>>a;
cin>>b;
lentha=lenth1=strlen(a)-1; ? ? ?// strlen()函数是计算这个字符串有多长的,返回值即为长度;
lenthb=lenth2=strlen(b)-1;
if(lenth1<lenth2)
{
k=lenth1; ? ? ? ? ? ? ? ? ? ? ? ? //找出较长的一个字符串
lenth1=lenth2;
lenth2=k;
}
for(i=lenth1,j=lenth2;j>=0;i--,j--)
{
c[i+1]=a[i]-'0'+b[j]-'0'; ? ? //因为这儿的字符是ASC码,减去0的ASC码后就是数字本身的大小了,然后保存到一个int数组中
}
if(lentha>lenthb)
{
for(j=i;j>=0;j--)
c[j+1]=a[j]-'0'; ? ? // 将较大的数加到数组中
}
else?
{
for(j=i;j>=0;j--)
c[j+1]=b[j]-'0';
}
c[0]=0; ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //这儿c[0]给它赋值为0;是因为两个数相加后,这个数的位数可能比最大的那个数的位数大1,也可能相等,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //所以c[0]是用来存可能要进一位的那个数的;
for(i=lenth1+1;i>=1;i--)
{
if(c[i]>=10) ? ? ? ? ? ? ? ? ? ? ? ? ?//判断如果这个数大于10,就取它的余数;然后让它的前面一位+1;这儿就是数大于10就进一位
? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? c[i]=c[i]%10;
c[i-1]=c[i-1]+1;
? ? ? ? ? ? ? ? ? ? }
}
if(c[0]!=0)
cout<<c[0];
for(i=1;i<=lenth1+1;i++) ? ?//输出结果
cout<<c[i];
cout<<"n";
}


接下来用Java做;

import java.math.*; ? ? ? ? ?a//java中有自带的大数; import java.util.*; public class Main{ public static void main(String args[]) { Scanner cin=new Scanner(System.in); while(cin.hasNext()) { BigInteger a=BigInteger.valueOf(1); BigInteger b=BigInteger.valueOf(1); a=cin.nextBigInteger(); b=cin.nextBigInteger(); System.out.println(a.add(b)); ? ? //不能写成a+b; } } }

(编辑:李大同)

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

    推荐文章
      热点阅读