43. Multiply Strings

来源:互联网 发布:手机数据可以恢复吗 编辑:程序博客网 时间:2024/06/05 14:52

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

Note:

  1. The length of both num1 and num2 is < 110.
  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.

模拟乘法运算过程。字符串数字num1和num2没有前导零,处理方便一些。程序如下:

class Solution {    public StringBuilder multiplySingleChar(String num1, char ch){        int carry = 0, val = 0;        StringBuilder s = new StringBuilder();        for (int i = num1.length() - 1; i >= 0; -- i){            s.insert(0, ((num1.charAt(i) - '0')*(ch - '0') + carry)%10);            carry = ((num1.charAt(i) - '0')*(ch - '0') + carry)/10;        }        if (carry != 0){            s.insert(0, carry);        }        return s;    }        public String addString(String num1, StringBuilder num2){        int carry = 0;        int index1 = num1.length() - 1, index2 = num2.length() - 1;        StringBuilder sum = new StringBuilder();        while (index1 >= 0&&index2 >= 0){            sum.insert(0, (num1.charAt(index1) - '0' + num2.charAt(index2) - '0' + carry)%10);            carry = (num1.charAt(index1) - '0' + num2.charAt(index2) - '0' + carry)/10;            index1 --;            index2 --;        }        while (index1 >= 0){            sum.insert(0, (num1.charAt(index1) - '0' + carry)%10);            carry = (num1.charAt(index1) - '0' + carry)/10;            index1 --;        }        while (index2 >= 0){            sum.insert(0, (num2.charAt(index2) - '0' + carry)%10);            carry = (num2.charAt(index2) - '0' + carry)/10;            index2 --;        }        if (carry > 0){            sum.insert(0, carry);        }        return new String(sum);    }        public String multiply(String num1, String num2) {        if (num1.equals("0")||num2.equals("0")){            return "0";        }        String val = new String("0");        for (int j = num2.length() - 1; j >= 0; -- j){            StringBuilder tmp = multiplySingleChar(num1, num2.charAt(j));            for (int i = num2.length() - 1; i > j; -- i){                tmp.append('0');            }            val = addString(val, tmp);        }        return val;    }}

本程序涉及大量的StringBuilder插入操作,效率较低,可通过字符数组的方式重新改写相关操作,效率会提高很多。



原创粉丝点击