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

Add Strings

时间:2018-01-23 23:16:34      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:log   常量   速度   present   pos   而不是   public   note   contain   

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.

         代码的主要思路就是一位一位相加。具体代码实现过程如下。

public String addStrings(String num1, String num2) {
        int len1 = num1.length() - 1;
        int len2 = num2.length() - 1;
        int add = 0;
        StringBuilder s = new StringBuilder();
        String tem = "";
        if (num1.length() >= num2.length()) {

            while (len2 >= 0) {
                int x = Integer.parseInt(num1.charAt(len1) + "") +
                        Integer.parseInt(num2.charAt(len2) + "") + add;
                tem = Integer.toString(x % 10);
                s.append(tem);
                add = x / 10;
                len1--;
                len2--;
            }
            
            if(len1>=0) {
                while (len1 >= 0) {
                    int x = Integer.parseInt(num1.charAt(len1) + "") + add;
                    tem = Integer.toString(x % 10);
                    s.append(tem);
                    add = x / 10;
                    len1--;
                }
            }
            if(add>0) {
                s.append(add);

            }


        }else {
         return addStrings(num2,num1);
        }
        return s.reverse().toString();
    }

但是关注了一下,评论区大神的代码。

StringBuilder sb = new StringBuilder();
        int carry = 0;
        for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){
            int x = i < 0 ? 0 : num1.charAt(i) - ‘0‘;
            int y = j < 0 ? 0 : num2.charAt(j) - ‘0‘;
            sb.append((x + y + carry) % 10);
            carry = (x + y + carry) / 10;
        }
        return sb.reverse().toString();

代码比我的简洁,另外在内存上也有很大程度的优化。这主要是string和stringbuffer的区别。string是字符串常量,而stringbuffer是字符串变量,简要的说,每次对string类型进行改变的时候其实等同于生成了一个新的string,仍后指针指向新的string对象,所以经常改变字符串最好不要用string因为每次生成对象都会对系统性能产生影响,特别当内存中无引用对象多了以后, JVM 的 GC 就会开始工作,那速度是一定会相当慢的。

如果是使用 StringBuffer 类则结果就不一样了,每次结果都会对 StringBuffer 对象本身进行操作,而不是生成新的对象,再改变对象引用。所以在一般情况下我们推荐使用 StringBuffer ,特别是字符串对象经常改变的情况下。

另外对z字符串转int类型可以不用integer转换,还可以对‘0‘,‘a‘,‘A’等做减法。

 

Add Strings

标签:log   常量   速度   present   pos   而不是   public   note   contain   

原文地址:https://www.cnblogs.com/liuchuan9504/p/8338079.html

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