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)
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"
.
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;
}
};