码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Multiply Strings

时间:2015-02-22 14:38:15      阅读:101      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!