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

Multiply Strings

时间:2016-08-02 06:33:34      阅读:129      评论: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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

分析:

把结果放在一个数组里,用startIndex来移动起始位置。

 1 public class Solution {
 2     public String multiply(String num1, String num2) {
 3         if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) return "";
 4         int[] result = new int[num1.length() + num2.length()];
 5         
 6         int startIndex = 0;
 7         for (int i = num1.length() - 1; i >= 0; i--) {
 8             int number1 = num1.charAt(i) - 0;
 9             int extra = 0;
10             for (int j = num2.length() - 1; j >= 0; j--) {
11                 int number2 = num2.charAt(j) - 0;
12                 int value = number1 * number2 + result[(result.length - 1) - startIndex + j - (num2.length() - 1)] + extra;  
13                 extra = value / 10;  
14                 value = value % 10;  
15                 result[(result.length - 1) - startIndex + j - (num2.length() - 1)] = value;                  
16             }  
17             result[(result.length - 1) - startIndex - 1 - (num2.length() - 1)] = extra;  
18             startIndex++;  
19         }  
20         String str = "";  
21         boolean isBeginningZero = true;  
22         for (int i = 0; i < result.length; i++) {  
23             if (!(result[i] == 0 && isBeginningZero == true)) {
24                 isBeginningZero = false;  
25                 str += result[i];  
26             }  
27         }  
28         return str == "" ? "0" : str;  
29     }
30 }

 

Multiply Strings

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5727811.html

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