最近在网上看到个求两个超大整数的和,如果用整数int表示的话,肯定会溢出,所以几乎所有人都想到用数组,没错,用数组或者字符串都可以,但是如果你在写程序的时候考虑到计算机是如何进行乘法,除法和加减法运算的,我想程序的效率会提高很多.
在两个数相加时,如果你这样判断:
if (a+b >= 10)
{
remains = (a+b) % 10;
array[i] = (a+b) / 10;
}
计算机会进行无数次的乘法和除法,而且做了三次加法运算,自然效率会低. 两个数相加,不会超过20,
所以可以这样做吧:
int result = a+b ;
remains = result >= 10 ? 1 : 0 ;
array[i] = remains == 0 ? result : result - 10 ;
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string first;
string second;
string result;
void AddIt()
{
int index = 0;
int tmpResult = 0;
int remains = 0;
string::reverse_iterator f_itor = first.rbegin();
string::reverse_iterator s_itor = second.rbegin();
result.resize(max(first.length(),second.length()),' ');
while( f_itor!=first.rend() && s_itor!=second.rend())
{
tmpResult = *f_itor -'0' + *s_itor - '0' + remains;
remains = tmpResult >=10 ? 1 : 0;
result[index] = remains == 0 ? tmpResult + '0' : (tmpResult - 10) + '0' ;
++f_itor;
++s_itor;
++index;
}
if (first.length() != second.length())
{
if (f_itor == first.rend())
{
while(s_itor!=second.rend())
{
tmpResult = *s_itor - '0' + remains ;
remains= tmpResult >=10 ? 1 : 0 ;
result[index] = remains == 0 ? tmpResult + '0' : (tmpResult - 10) + '0' ;
++s_itor;
++index;
}
}
else
{
while(f_itor!=first.rend())
{
tmpResult = *f_itor - '0' + remains ;
remains= tmpResult >=10 ? 1 : 0 ;
result[index] = remains == 0 ? tmpResult + '0' : (tmpResult - 10) + '0' ;
++f_itor;
++index;
}
}
if (remains != 0)
result.resize(result.length()+1,remains + '0');
}
reverse(result.begin(),result.end());
};
int main()
{
int testcases = 0;
cin >> testcases;
for(int i=0;i<testcases;i++)
{
cin >> first >> second;
AddIt();
cout << result.data() <<endl;
result = "";
}
return 0;
}
超大整数的和,基本功修炼
最新推荐文章于 2025-06-27 23:05:46 发布