简介
简单题, 按照正常人的思路即可
code
C++代码写复杂了, 应该, 补0的话可以省去判断谁是长字符串谁是短字符串
class Solution {
public:
string addStrings(string num1, string num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int n1 = num1.size();
int n2 = num2.size();
vector<int> c;
if(n1 >= n2) {
c.resize(n1+1, 0);
for(int i=0; i<n2; i++){
if(c[i] + num1[i] + num2[i] - '0' - '0' > 9){
c[i] = c[i] + num1[i] + num2[i] - '0' - '0' - 10;
c[i+1] += 1;
}else{
c[i] = c[i] + num1[i] + num2[i] - '0' - '0';
}
}
for(int i=n2; i<n1; i++) {
if(c[i] + num1[i] - '0' > 9){
c[i] = c[i] + num1[i] - '0' - 10;
c[i+1] += 1;
}else{
c[i] = c[i] + num1[i] - '0';
}
}
}else{
c.resize(n2+1, 0);
for(int i=0; i<n1; i++){
if(c[i] + num1[i] + num2[i] - '0' - '0' > 9){
c[i] = c[i] + num1[i] + num2[i] - '0' - '0' - 10;
c[i+1] += 1;
}else{
c[i] = c[i] + num1[i] + num2[i] - '0' - '0';
}
}
for(int i=n1; i<n2; i++) {
if(c[i] + num2[i] - '0' > 9){
c[i] = c[i] + num2[i] - '0' - 10;
c[i+1] += 1;
}else{
c[i] = c[i] + num2[i] - '0';
}
}
}
string rlt;
for(int i=0; i<c.size(); i++){
if(i == c.size() - 1) {
if(c[i] == 0) {
continue;
}
}
rlt += '0' + c[i];
}
reverse(rlt.begin(), rlt.end());
return rlt;
}
};
class Solution {
public String addStrings(String num1, String num2) {
int i = num1.length()- 1, j = num2.length() - 1, add = 0;
StringBuffer ans = new StringBuffer();
while(i >= 0 || j >=0 || add != 0) {
int x = i >=0 ? num1.charAt(i) - '0' : 0;
int y = j >= 0? num2.charAt(j) - '0' : 0;
int result = x + y + add;
ans.append(result % 10);
add = result / 10;
i--;
j--;
}
ans.reverse();
return ans.toString();
}
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》