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

Leetcode: Multiply Strings

时间:2014-09-05 12:36:41      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   for   div   代码   

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.

大整数的字符串乘法,我本来对字符串表示的大整数就不是太熟悉,至于溢出该怎么处理也是不大清楚,所以参考了别人的做法,然后自己凭着印象重做了一次

    • 直接乘会溢出,所以每次都要两个single digit相乘,最大81,不会溢出。
    • 比如385 * 97, 就是个位=5 * 7,十位=8 * 7 + 5 * 9 ,百位=3 * 7 + 8 * 9 …
      可以每一位用一个Int表示,存在一个int[]里面。
    • 这个数组最大长度是num1.len + num2.len,比如99 * 99,最大不会超过10000,所以4位就够了。
    • 这种个位在后面的,不好做(10的0次方,可惜对应位的数组index不是0而是n-1),
      所以干脆先把string reverse了代码就清晰好多。
    • 最后结果前面的0要清掉。

这里面的方法比较巧妙,也比较典型,需要掌握。还有需要注意溢出处理,这里的处理是:如果最高位产生进位carry,那么直接忽略这个carry

 1 public class Solution {
 2     public String multiply(String num1, String num2) {
 3         num1 = new StringBuffer(num1).reverse().toString();
 4         num2 = new StringBuffer(num2).reverse().toString();
 5         int[] n1 = new int[num1.length()];
 6         int[] n2 = new int[num2.length()];
 7         int[] temp = new int[num1.length() + num2.length()];
 8         for (int i = 0; i < num1.length(); i++) {
 9             n1[i] = (int)(num1.charAt(i) - ‘0‘); 
10             for (int j = 0; j < num2.length(); j++) {
11                 n2[j] = (int)(num2.charAt(j) - ‘0‘);
12                 temp[i + j] += n1[i] * n2[j]; 
13             }
14         }
15         
16         StringBuffer sb = new StringBuffer();
17         int digit = 0;
18         int carry = 0;
19         for (int k = 0; k < temp.length; k++) {
20             digit = temp[k] % 10;
21             carry = temp[k] / 10;
22             sb.insert(0, digit);
23             if (k < temp.length - 1) {
24                 temp[k + 1] += carry;
25             }
26         }
27         
28         while (sb.length() > 0 && sb.charAt(0) == ‘0‘) {
29             sb.deleteCharAt(0);
30         }
31         return sb.length() == 0? "0" : sb.toString();
32     }
33 }

 

Leetcode: Multiply Strings

标签:style   blog   color   os   io   ar   for   div   代码   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3957599.html

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