码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 415 字符串相加

时间:2021-05-24 12:50:46      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:java   tor   i++   etc   new   ret   字符串   har   ||   

简介

简单题, 按照正常人的思路即可

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();
    }
}

leetcode 415 字符串相加

标签:java   tor   i++   etc   new   ret   字符串   har   ||   

原文地址:https://www.cnblogs.com/eat-too-much/p/14774217.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!