LeetCode - 66/67 - 两数相加加法模拟
2017-07-18 09:52
465 查看
66 - Plus One
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
题意:将这个数组的数当做一个整数,数组的开始是这个整数的最高位。然后在这个整数上+1,求这个整数是多少
倒着模拟一遍就好,如果最后有进位,就在数组开始处插入1。时间复杂度O(n),空间复杂度O(1)
67. Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
模拟加法,时间复杂度O(n),空间复杂度O(n)
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
题意:将这个数组的数当做一个整数,数组的开始是这个整数的最高位。然后在这个整数上+1,求这个整数是多少
倒着模拟一遍就好,如果最后有进位,就在数组开始处插入1。时间复杂度O(n),空间复杂度O(1)
class Solution { public: vector<int> plusOne(vector<int>& digits) { int num = 1; for (int i = digits.size() - 1; i >= 0; --i) { digits[i] += num; num = digits[i] / 10; digits[i] %= 10; } if (num) digits.insert(digits.begin(), 1); return digits; } };
67. Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a =
"11"
b =
"1"
Return
"100".
模拟加法,时间复杂度O(n),空间复杂度O(n)
class Solution { public: string addBinary(string a, string b) { vector<int> ans; int i, j; int num = 0; for (i=a.length()-1, j=b.length()-1; i >= 0 && j >= 0; --i, --j) { int x = (a[i] - '0') + (b[j] - '0') + num; ans.push_back(x % 2); num = x / 2; } while (i >= 0) { int x = (a[i--] - '0') + num; ans.push_back(x % 2); num = x / 2; } while (j >= 0) { int x = (b[j--] - '0') + num; ans.push_back(x % 2); num = x / 2; } if (num) ans.push_back(num); string res = ""; for (int i = ans.size() - 1; i >= 0; --i) { if (ans[i]) res += "1"; else res += "0"; } return res; } };
相关文章推荐
- 2.4-链表模拟整数加法(same in LeetCode)
- Leetcode刷题记——67. Add Binary(二进制数相加)
- LeetCode 67 Add Binary(二进制相加)(*)
- 刷LeetCode(1)——两数相加
- 【LeetCode】66 & 67- Plus One & Add Binary
- [LeetCode] Add Two Numbers 两数相加
- LeetCode 2. Add Two Numbers(两数相加)
- LeetCode 2. 两数相加
- [LeetCode] 67. Add Binary 二进制数相加
- Leetcode 67 Add Binary 大数加法+字符串处理
- 【LeetCode】415. Add Strings,用string模拟加法
- [LeetCode]67 二进制相加
- 链表:链表两数相加( LeetCode 2. Add Two Numbers(两数相加))
- LeetCode 02. 两数相加(链表) 03.最大不重复的字符串
- [leetcode]两数相加
- leetcode 66.Plus One(简单大数模拟)
- Leetcode 67. Add Binary 二进制加法 解题报告
- LeetCode-67 Add Binary(二进制数相加)
- LeetCode 67. Add Binary (二进制相加)
- Leetcode 第二题,两数链表相加