码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode: Multiply Strings. Java

时间:2014-10-29 09:14:28      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   string   

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.

public class Solution {
    //模拟手算乘法
    public String multiply(String num1, String num2) {
        int n = num2.length();
        String[] addS = new String[n];
        for(int i = 0; i < n; i++){
            addS[i] = multiplyChar(num1, num2.charAt(i), n-1-i);
        }
        String res = sum(addS);
        int p = 0;
        while(p < res.length() && res.charAt(p) == '0')
        	p++;
        if(p == res.length())
        	return "0";
        else 
        	return res.substring(p);
    }
    
    public String multiplyChar(String num, char c, int digits){
        int n = num.length();
        char[] res = new char[n + 1];
        int add = 0;
        for(int i = n; i >= 0; i--){
            int b = 0;
            if(i-1 >= 0)
                b = num.charAt(i-1)-'0';
            int cur = b*(c-'0')+add;
            add = cur / 10;
            cur %= 10;
            res[i] = (char)(cur+'0');
        }
        int p = 0;
        while(p <= n && res[p] == '0')
            p++;
        if(p == n + 1)
        	return "0";
        else{
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < digits; i++){
                sb.append('0');
            }
        	return new String(res, p, n-p+1) + sb.toString();
        }
    }
    
    public String sum(String[] s){
        StringBuffer res= new StringBuffer();
        int p = 0;
        int cur = 0;
        int add = 0;
        int maxLength = 0;
        for(int i = 0; i < s.length; i++){
            maxLength = Math.max(maxLength, s[i].length());
        }
        do{
        	cur = 0;
            for(int i = 0; i < s.length; i++){
                if(p < s[i].length())
                    cur += s[i].charAt(s[i].length()-1-p)-'0';
            }
            cur += add;
            res.append(cur%10);
            add = cur / 10;
            p++;
        }
        while(cur != 0 || p < maxLength);
        return new String(res.reverse());
    }
}


LeetCode: Multiply Strings. Java

标签:java   leetcode   string   

原文地址:http://blog.csdn.net/muscler/article/details/40580949

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!