LeetCode 415. Add Strings 题解(C++)
来源:互联网 发布:鹏鹏扣字软件谁? 编辑:程序博客网 时间:2024/05/21 21:38
LeetCode 415. Add Strings 题解(C++)
题目描述
- Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
补充
- 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.
思路
- 该算法为大数相加使用字符串string实现的问题。首先算出两个字符串的长度,并从两个字符串的最后一个字符开始循环,两个字符串对应位置的值相加,若有进制,则保存。若某一字符串的长度较长,需要将该字符串剩下的字符遍历完成,所以循环退出的条件是i>=0||j>=0;
- 这里需要注意的是对字符串位置的操作,需要从两个给定字符串的最后一个位置开始,并且每次得到的结果应放置到结果字符串的首位置。
- 对于数字和字符的相互转换,这里需要用到‘0’。
代码
class Solution {public: string addStrings(string num1, string num2) { string num; int length1 = num1.length(); int length2 = num2.length(); int carry = 0; for (int i = length1 - 1, j = length2 - 1; i >= 0 || j >= 0; --i, --j) { int temp = 0; if (i >= 0) { temp += num1[i] - '0'; } if (j >= 0) { temp += num2[j] - '0'; } if (carry) { ++temp; } carry = temp / 10; temp = temp % 10; num = char(temp + '0') + num; } if (carry) { num = char(carry + '0') + num; } return num; }};
0 0
- LeetCode 415. Add Strings 题解(C++)
- 【leetcode 题解】415. Add Strings【E】
- LeetCode 415. Add Strings题解 字符串加和
- Leetcode-415. Add Strings
- LeetCode 415. Add Strings
- [LeetCode]--415. Add Strings
- LeetCode 415. Add Strings
- LeetCode 415. Add Strings
- LeetCode 415. Add Strings
- leetcode 415. Add Strings
- 【LeetCode】 415. Add Strings
- LeetCode 415. Add Strings
- Leetcode 415. Add Strings
- LeetCode - 415. Add Strings
- LeetCode 415. Add Strings
- Leetcode 415. Add Strings
- Leetcode-415. Add Strings
- LeetCode-415. Add Strings
- R语言各种查询
- Hdfs 的读写操作
- 基于开源jabber(XMPP)架设内部即时通讯服务的解决方案
- 关于Avoid non-default constructors in fragments的错误
- Android 设计模式 之 单例模式
- LeetCode 415. Add Strings 题解(C++)
- linux IPC--信号量
- js如何获取对象中的属性名
- 反编译相关记录
- Solr开发文档
- "打开方式"打开本地文件,获取文件路径
- 超全的css新手学习笔记
- ThinkPHP上传文件时,使用var_dump($_FILES)输出数组为空的解决办法。
- QT基础(一)