[Leetcode]-- Multiply Strins

[Leetcode]-- Multiply Strins
public class Solution {
    public String multiply(String num1, String num2) {
        int l1 = num1.length();
        int l2 = num2.length();
        
        int[] num = new int[l1 + l2 + 1];
        for(int i = 0; i <= l2 - 1; i ++){
            int carry = 0;
            int a = num2.charAt(l2 - 1 - i) - ‘0‘;
            for(int j = 0; j <= l1 - 1; j ++){
                int b = num1.charAt(l1 - 1 - j) - ‘0‘;
                num[i + j] += a * b + carry;
                carry = num[i + j] / 10;
                num[i + j] = num[i + j] % 10;
            }
            // 123*9 carry add to the left side of digit ‘1‘
            num[i + l1] = carry;
        }
        
        // 100 * 1 = 00100 把00100 转换为 100
        int i  = num.length -1;
        while( i > 0 && num[i] == 0){
            i--;
        }
        
        StringBuilder sb = new StringBuilder();
        while(i >= 0){
            sb.append(num[i--]);
        }
        return sb.toString();

    }
}
[Leetcode]-- Multiply Strins

[Leetcode]-- Multiply Strins

上一篇:如何有规律的备份 WordPress 博客(转)


下一篇:Entity Framework在WCF中序列化的问题(转)