Multiply Strings

来源:互联网 发布:ps pc版和mac版差别 编辑:程序博客网 时间:2024/06/03 21:43

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note:

  • The numbers can be arbitrarily large and are non-negative.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

也是参考了网上的一种比较巧妙的解法,将元素逆序,这样做乘法的时候可以从0走起。在生成结果的时候,从低位开始算起,结果是正序插入的(每次insert在index = 0 的位置),并且在插入的过程中计算进位。对于if(i<result.length-1){ result[i+1]  += carry; } 我的理解是,对于生成的结果,最大长度不会超过num1.length+num2.length,那么在最高位上,是一定不会有进位的,所以除了最高位,都要加上carry这个变量,因为carry可能不为0.

后续会再整理一遍。 

public String multiply(String num1, String num2) {        int [] result = new int[num1.length() + num2.length()];        String num1R = new StringBuffer(num1).reverse().toString();        String num2R = new StringBuffer((num2)).reverse().toString();        for(int i=0;i<num1R.length();i++){            for(int j=0;j<num2R.length();j++){                result[i+j]  += (num1R.charAt(i)-'0') * (num2R.charAt(j)-'0');            }        }        StringBuffer sb = new StringBuffer();        for(int i=0;i<result.length;i++){            int digit = result[i] % 10;            int carry = result[i] / 10;            sb.insert(0, digit);            if(i<result.length-1){                result[i+1]  += carry;            }        }        //结果已经正向存进去了        while(sb.length()>0 && sb.charAt(0) =='0'){            sb.deleteCharAt(0);        }        return sb.length() == 0 ?"0":sb.toString();    }

dfasdf



s

dfsd


0 0
原创粉丝点击