Java solution share

  • 0
    public class Solution {
    public String multiply(String num1, String num2) {
        //prepare map;
        if(num1.equals("0")|| num2.equals("0")) return "0";//string 相等不能用==号
        String temp =num1;
        HashMap <Character, String> lookup = new HashMap<Character, String>(){{ put('0',"0"); put('1',num1); }};
        for(int i=2; i<=9; i++){
            temp = add(temp, num1);
            char index = (char)('0'+i);
            lookup.put(index, temp);
        String ans="0";
        String temp1 = "";
        for(int i=num2.length()-1; i>=0; i--){
            String bitemp =lookup.get(num2.charAt(i));
            bitemp = bitemp+temp1;
            ans=add(ans, bitemp);
        return ans;
    private String add(String num1, String num2){
        StringBuilder sb = new StringBuilder();
            String temp =num1;
        int i,j;
        int carry=0;
        for(i=num2.length()-1, j=num1.length()-1; i>=0; i--,j--){
         int temp = num1.charAt(j)-'0'+0+num2.charAt(i)-'0'+carry;
         sb.insert(0, temp%10);
         carry = temp/10;
          for(; j>=0;j--){
            int temp = num1.charAt(j)-'0'+carry;
            sb.insert(0, temp%10);
            carry = temp/10;
        sb.insert(0, '1');
        return sb.toString();


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.