大整数相加问题

在计算机中,由于处理器位宽限制,只能处理有限精度的十进制整数加减法,比如在32位处理器计算机中,参与运算的操作数和结果必须在**之间。如果需要进行更大范围的十进制整数加法,需要使用特殊的方式实现,比如使用字符串保存操作数和结果,采取逐位运算的方式。比如下面问题:

9876543210 + 1234567890 =?

让字符串 num1 = "9876543210",字符串 num2 = "1234567890",结果保存在字符串result中。要求编程实现上述高精度的十进制加法。

01 #include<stdio.h>
02 #include<string.h>
03 int NumAdd(const char *first,const char *second,char *result, int resultlen)
04 {
05     int numlen[2];
06     numlen[0] = strlen(first);
07     numlen[1] = strlen(second);
08     int maxlen;
09     maxlen=  numlen[0]> numlen[1] ?  numlen[0] : numlen[1] ;
10       
11     if (resultlen< maxlen + 1)     
12         return -1;
13   
14     int n;
15     int byteValue[2];
16     int curByteResult;
17     int addByteResult;
18   
19     curByteResult=addByteResult=0;
20  
21     //从左到右进行循环
22     for(n = 0; n <maxlen; n++)
23     {
24         --numlen[0];
25         --numlen[1];
26  
27         if (numlen[0] >= 0)
28             byteValue[0] = first[n] - '0' ;
29         else
30             byteValue[0] = 0 ;  
31   
32         if (numlen[1] >= 0)
33             byteValue[1] = second[n]- '0' ;
34         else
35             byteValue[1] = 0 ;  
36      
37         curByteResult = byteValue[0] +  byteValue[1];
38         if (curByteResult>=10)
39         {
40             curByteResult -= 10;
41             addByteResult = 1;
42   
43             if (n==0)
44             {
45                 result[0] = '1';
46                 ++result;
47             }
48             else
49             {
50                 ++result[n-1]; //处理进位
51             }
52             result[n] = '0'+curByteResult; 
53         }
54         else
55         {
56             result[n] = '0'+curByteResult ;
57             addByteResult = 0;
58         }
59     }
60     result[n] =0;
61     return 1;
62 }
63  
64  
65 int main( )
66 {
67     char szstr1[]="9876543210";
68     char szstr2[]="1234567890";
69     char result[100];
70   
71     NumAdd(szstr1,szstr2,result,100);
72     printf("result is %s ",result);
73  
74     return 0;
75 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值