[Java] There are some tricky margin problems, be careful


  • 0
    H
    public class Solution {
        public String multiply(String num1, String num2) {
            
            int len1 = num1.length(), len2 = num2.length(), temp = 0;
            int[] res = new int[len1 + len2];
            
            for(int i = len1 -1; i>=0; i--){
                for(int j = len2 -1; j>=0; j--){
                    res[i+j+1] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                    int n = -1;
                    if(res[i+j-n] >9){
                        res[i+j-n-1] += res[i+j-n]/10;
                        res[i+j-n] = res[i+j-n]%10;
                        n++;
                    }
                }
            }
            char[] tempRes = new char[len1 + len2];
            for(int i = 0; i<len1+len2; i++) tempRes[i] = (char)(res[i] + 48);
            
            StringBuffer s = new StringBuffer(new String(tempRes));
            while(s.charAt(0) =='0' && s.length()>1) s.deleteCharAt(0);
            return s.toString();
        }
    }

Log in to reply
 

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