• 415. Add Strings


    Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

    Note:

    1. The length of both num1 and num2 is < 5100.
    2. Both num1 and num2 contains only digits 0-9.
    3. Both num1 and num2 does not contain any leading zero.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
    
    
    class Solution {
        public String addStrings(String num1, String num2) {
            int l1 = num1.length();
            int l2 = num2.length();
            int carry = 0;
            int c1 = l1-1, c2 = l2-1;
            StringBuilder res = new StringBuilder();
            while(c1 >= 0 || c2 >= 0){
                int cur1 = c1 >= 0 ? (num1.charAt(c1) - '0') : 0;
                int cur2 = c2 >= 0 ? (num2.charAt(c2) - '0') : 0;
                int sum = cur1 + cur2 + carry;
                int digit = sum % 10;
                carry = sum / 10;
                res.insert(0, digit);
                if(c1 >= 0) c1--;
                if(c2 >= 0) c2--;
            } 
            if(carry == 1){
                res.insert(0, 1);
                System.out.println(carry);
            }
                
            return res.toString();
        }
    }
    
    
    
     

    和add two numbers差不多

  • 相关阅读:
    取球问题
    汉字首字母
    上三角
    循环小数
    拓扑排序
    倒水
    equals方法使用技巧
    Java库中的集合
    win10安装Redis方法以及基本配置
    c、c++函数随机
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13053767.html
Copyright © 2020-2023  润新知