Leetcode no. 43

来源:互联网 发布:淘宝开店交税吗 编辑:程序博客网 时间:2024/05/18 22:17

43. Multiply Strings


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.

public class Solution {    public String multiply(String num1, String num2) {        int[] res= new int[num1.length()+num2.length()];        for (int i = num1.length()-1; i >=0 ; i--) {            for (int j = num2.length()-1; j >=0 ; j--) {                int tmp= (num1.charAt(i)-'0')*(num2.charAt(j)-'0');                int sum= tmp+ res[i+j+1];                res[i+j]+= sum/10;                res[i+j+1]= sum%10;            }        }        StringBuilder sb= new StringBuilder();        for (int ele: res) {            if (sb.length()!=0 || ele!=0) sb.append(ele);        }        return sb.length()==0 ? "0" : sb.toString();    }}


0 0
原创粉丝点击