Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1445836
  • 博文数量: 254
  • 博客积分: 8696
  • 博客等级: 中将
  • 技术积分: 2961
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-03 16:46
文章分类

全部博文(254)

文章存档

2015年(4)

2014年(18)

2013年(16)

2012年(8)

2011年(25)

2010年(2)

2009年(74)

2008年(107)

分类: C/C++

2011-04-29 14:35:41

  1. #include <QtCore/QCoreApplication>
  2. #include <string.h>
  3. #include <QTextCodec>
  4. #include <iostream>
  5. using namespace std;

  6. void SumStr(const string &strA, const string &strB, string &strResult)
  7. {
  8.     //确保左操作数的位数大于右操作数
  9.     int nLeftLen = strA.size();
  10.     int nRightLen = strB.size();
  11.     string strLeft = nLeftLen > nRightLen ? strA : strB;
  12.     string strRight = nLeftLen > nRightLen ? strB : strA;
  13.     nLeftLen = strLeft.size();
  14.     nRightLen = strRight.size();
  15.     strResult.reserve(nLeftLen+1);

  16.     int nTmp = 0;
  17.     char cTmp[2]={0};

  18.     //两数相加
  19.     for(int i=0; i<nRightLen; i++)
  20.     {
  21.         nTmp = strLeft.at(nLeftLen-1-i) - '0' + strRight.at(nRightLen-1-i) - '0' + nTmp;
  22.         cTmp[0] = nTmp%10+'0';
  23.         strResult.insert(0, cTmp);
  24.         nTmp /= 10;
  25.     }

  26.     //相加后进位处理
  27.     int nMin = nRightLen;
  28.     while(0 != nTmp && nMin < nLeftLen)
  29.     {
  30.         nTmp = strLeft.at(nLeftLen-1-nMin) - '0' + nTmp;
  31.         cTmp[0] = nTmp%10+'0';
  32.         strResult.insert(0, cTmp);
  33.         nTmp /= 10;
  34.         ++nMin;
  35.     }

  36.     //左操作数剩下的位数没有参与相加
  37.     if(nMin < nLeftLen)
  38.     {
  39.         string strBub = strLeft.substr(0, nLeftLen-nMin);
  40.         strResult.insert(0, strBub);
  41.     }

  42.     //高位进位
  43.     if(0 != nTmp)
  44.     {
  45.         cTmp[0] = '1';
  46.         strResult.insert(0, cTmp);
  47.     }
  48. }

  49. int main(int argc, char *argv[])
  50. {
  51.     QCoreApplication a(argc, argv);
  52.     QTextCodec::setCodecForTr(QTextCodec::codecForName("gb2312"));
  53.     string strA("8794513");
  54.     string strB("6847897984651");
  55.     string strResult;
  56.     strResult.clear();
  57.     SumStr(strA, strB, strResult);

  58.     cout<<strA << "+" << strB << "= " << strResult.data();

  59.     return a.exec();
  60. }
阅读(2465) | 评论(0) | 转发(0) |
0

上一篇:基于散列的查找

下一篇:函数指针数组

给主人留下些什么吧!~~