美文网首页
415. Add Strings

415. Add Strings

作者: AlanGuo | 来源:发表于2016-10-09 15:47 被阅读0次

    Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.
    Note:
    The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9.
    Both num1 and num2 does not contain any leading zero.
    You must not use any built-in BigInteger library or convert the inputs to integer directly

    Solution:

    惊了,将两个字符串转换为 long 再相加,再将 result 转换为 String,居然不对?代码留在这里先:

    /*
     * This code is wrong.
     */
    
    public class Solution
    {
        public String addStrings(String num1, String num2)
        {
            long num1Int = 0, num2Int = 0;
            for (int i = num1.length() - 1; i >= 0; i--)
            {
                num1Int += (int)(num1.charAt(i) - '0') * Math.pow(10, num1.length() - i - 1);
            }
    
            for (int i = num2.length() - 1; i >= 0; i--)
            {
                num2Int += (int)(num2.charAt(i) - '0') * Math.pow(10, num2.length() - i - 1);
            }
            long result = num1Int + num2Int;
            return String.valueOf(result);
        }
    }
    
    Input:
    "9333852702227987" 
    "85731737104263"
    
    Output:
    "9419584439332251"
    
    Expect:
    "9419584439332250"
    

    最高位为9就不对了……溢出?还多1……why?

    看了 Discussion 发现都在模拟竖式加法…………先这么写吧……还从来没有模拟过竖式加法就当练习了

    public class Solution 
    {
        public String addStrings(String num1, String num2) 
        {
            int i = num1.length() - 1;
            int j = num2.length() - 1;
            int carry = 0;
            String result = new String();
            while(i >= 0 || j >= 0 || carry >0)
            {
                int sum = 0;
                if(i >= 0)
                {
                    sum += num1.charAt(i) - '0';
                }
                if(j >= 0)
                {
                    sum += num2.charAt(j) -'0';
                }
                sum += carry;
                carry = (int)sum / 10;
                sum = sum % 10;
                result = String.valueOf(sum) + result;
                i--; 
                j--;
            }
            return result;
        }
    }
    

    相关文章

      网友评论

          本文标题:415. Add Strings

          本文链接:https://www.haomeiwen.com/subject/sxopyttx.html