Big Integer Addition存储在字符串内的整数相加
来源:互联网 发布:高斯滤波matlab算法 编辑:程序博客网 时间:2024/05/18 02:40
题目:
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
andnum2
.
注意事项
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路:
char array与string类型的转换,特殊边界的处理
class Solution {public: /* * @param num1: a non-negative integers * @param num2: a non-negative integers * @return: return sum of num1 and num2 */ string addStrings(string &num1, string &num2) { // write your code here int len1 = num1.size(); int len2 = num2.size(); string fres; if (len1 < len2) { int tmp = len1; len1 = len2; len2 = tmp; string tmpstr = num1; num1 = num2; num2 = tmpstr; } char res[len1+1]; int index2 = len2-1; res[len1-1] = 0; for (int i = len1-1; i > 0; i--) { if (i > len1-len2-1) { if ( res[i]+num1[i] + num2[index2] -'0'-'0' >=10) { res[i] += num1[i]+num2[index2]-'0'-10; res[i-1] = 1; } else { res[i] += num1[i]+num2[index2]-'0'; res[i-1] = 0; } index2 -= 1; } else { if ( res[i]+num1[i] -'0' >=10) { res[i] += num1[i]-10; res[i-1] = 1; } else { res[i] += num1[i]; res[i-1] = 0; } } } if (len1 == len2) { if ( res[0]+num1[0]+num2[0] -'0' -'0' >= 10) { res[0] += num1[0]+num2[0]-'0'-10; char res2[len1+2]; for (int i = 0; i < len1; i++) { res2[i+1] = res[i]; } res2[0] = '1'; fres.assign(res2, len1+1); } else { res[0] += num1[0]+num2[0]-'0'; fres.assign(res, len1); } } else { if ( res[0]+num1[0] -'0' >= 10) { res[0] += num1[0]-10; char res2[len1+2]; for (int i = 0; i < len1; i++) { res2[i+1] = res[i]; } res2[0] = '1'; fres.assign(res2, len1+1); } else { res[0] += num1[0]; fres.assign(res, len1); } } return fres; }};
阅读全文
0 0
- Big Integer Addition存储在字符串内的整数相加
- Big Integer Addition
- [Amazon] Big Integer Addition
- Big Integer Addition
- Big Integer Addition
- LintCode :Big Integer Addition
- lintcode(655)Big Integer Addition
- hdoj1047 Integer Inquiry(大整数的相加)
- Google/LintCode:E-Big Integer Addition
- POJ 1503 Integer Inquiry 美丽的大整数相加 + 测试数据
- Problem A+B(Big Integer)大数相加
- LintCode python 小白4-Big Integer Addition
- 两个32位无符号长整数相加的函数,相加之和不能存储在64位变量中
- 两个整数字符串相加
- 字符串整数相加
- 请用C语言在32位环境下,两个无符号长整数相加的函数,相加之和不能存储在64位变量中
- 计算机内存储整数的总结
- 字符串与整数相加 整数占字符串的最后几位
- Servlet--慕课网笔记
- OneProxy6.1.3 读写分离配置
- opencv3学习(1)
- 动漫收藏
- 仿3D效果的实现
- Big Integer Addition存储在字符串内的整数相加
- iOS开发-由浅至深学习block
- Android中View和ViewGroup介绍
- Android studio上传项目到gitHub(超级详细)
- 搜索系统5:搭建Solr Cloud环境
- javascript处理json/base64等数据并且下载成本地json/image文件(angular环境、execCommand)
- 学习索引
- netty源码分析之LengthFieldBasedFrameDecoder
- Webview调用相册相机失败等问题(h5交互问题)