Multiply Strings (Java)

来源:互联网 发布:大数据 入门书籍 编辑:程序博客网 时间:2024/06/07 01: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.

先把每一位乘出来的数存起来,然后再集体处理进位。

Source

public class Solution {    public String multiply(String num1, String num2) {        if(num1.equals("0") || num2.equals("0")) return "0";    StringBuffer x1 = new StringBuffer(num1);        StringBuffer x2 = new StringBuffer(num2);        x1.reverse();//大数乘法一般都倒过来存,比较好处理 尤其是两个数位数不一样时        x2.reverse();//如果不reverse的话 数组第0位存的是最高位        int[] num = new int[x1.length() + x2.length()];  //相乘,数组要开的大                for(int i = 0; i < x1.length(); i++){        int a = x1.charAt(i) - '0';//***注意减去0        for(int j = 0; j < x2.length(); j++){        int b = x2.charAt(j) - '0';        num[i + j] += a * b;                }        }                StringBuffer res = new StringBuffer();        for(int i = 0; i < num.length; i++){        int temp = num[i] % 10;        int carry = num[i] / 10;        res.insert(0, temp);//正着存        if(i < num.length - 1) num[i + 1] += carry;                }                while(res.charAt(0) == '0'){        res.deleteCharAt(0);        }        return res.toString();    }}


Test

   public static void main(String[] args){    String num1 = "1";    String num2 = "2";    System.out.println(new Solution().multiply(num1, num2));    }


0 0
原创粉丝点击