首页 > 其他 > 详细

Leetcode: Multiply Strings

时间:2015-02-22 14:36:53      阅读:268      评论:0      收藏:0      [点我收藏+]

Problem:

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.



Solution:

multiply  each bit of string 1 with string2.  Be careful of the carryIn and the position.



Code:

public class Solution {
    public String multiply(String num1, String num2) {
        if ( num1 == null || num2 == null) return "";
        int[] result = new int[num1.length() + num2.length()];
        int carryIn = 0;
        for (int i = num1.length() - 1; i >= 0; i--) {
            carryIn = 0;
            for (int j = num2.length() - 1; j >= 0; j--) {
                int a = num1.charAt(i) - '0';
                int b = num2.charAt(j) - '0';
                int tmp = a * b + carryIn + result[num1.length() - 1 + num2.length() - 1 - i - j];
                carryIn = tmp / 10;
                result[num1.length() - 1 + num2.length() - 1 - i - j] = tmp % 10;
            }
            result[num1.length() - 1 + num2.length() - 1 - i + 1] = carryIn;
        }
      //  result[num1.length() + num2.length() - 1] = carryIn;
        int i = num1.length() + num2.length() - 1;
        while (i >= 1 && result[i] == 0) {
            i--;
        } 
        String s = "";
        for (int j = i; j >= 0; j--) {
            s = s + result[j];
        }
        return s;
    }
}


Leetcode: Multiply Strings

原文:http://blog.csdn.net/luckyseven7777/article/details/43907187

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!