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

43.Multiply Strings

时间:2015-04-10 07:03:41      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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:直接乘会溢出,需要一位一位的乘。

 用一个数组d[]装所有一位乘积。

正确算法:

public class Solution {
    public String multiply(String num1, String num2) {
   
        String s1=new StringBuilder(num1).reverse().toString();
        String s2=new StringBuilder(num2).reverse().toString();
        int[] d= new int[s1.length()+s2.length()];
        for(int i=0;i<s1.length();i++){
            for(int j=0;j<s2.length();j++){
                d[i+j]=d[i+j]+(s1.charAt(i)-‘0‘)*(s2.charAt(j)-‘0‘);
            }
        }
        StringBuilder sb=new StringBuilder();
        int carry;
        int digit;
        for(int temp=0;temp<d.length;temp++){
            digit=d[temp]%10;
            carry=d[temp]/10;
            sb.insert(0,digit);
            if(temp<d.length-1)
            d[temp+1]=d[temp+1]+carry;
        }
    
        while(sb.length()>0 && sb.charAt(0)==‘0‘){
            sb.deleteCharAt(0);
        }
       if(sb.length()==0){
            return "0";
        }
        return sb.toString();
    }
}

 

43.Multiply Strings

标签:

原文地址:http://www.cnblogs.com/joannacode/p/4413406.html

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