zoukankan      html  css  js  c++  java
  • 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差不多

  • 相关阅读:
    tableau用户留存分析
    tableau用户分类
    业务
    数据分析的思维技巧-二
    数据分析的思维技巧
    业务化思维
    公式化思维
    结构化思维
    Shortest Unsorted Continuous Subarray
    Longest Harmonious Subsequence
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13053767.html
Copyright © 2011-2022 走看看