leetcode--Multiply Strings

来源:互联网 发布:淘宝为什么屏蔽神武 编辑:程序博客网 时间:2024/06/16 00:37

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.

[java] view plain copy
  1. public class Solution {  
  2.     public String multiply(String num1, String num2) {  
  3.         int[] res = new int[num1.length()+num2.length()];  
  4.         for(int i=num1.length()-1;i>=0;i--){           
  5.             for(int j=num2.length()-1;j>=0;j--){  
  6.                 int n1 = num1.charAt(i)-'0';  
  7.                 int n2 = num2.charAt(j)-'0';  
  8.                 res[i+j+1] += n1*n2;  
  9.             }  
  10.         }  
  11.         int flag = 0;         
  12.         for(int i=res.length-1;i>=0;i--){  
  13.             int tmp = (res[i] + flag) % 10;  
  14.             flag = (res[i] + flag) / 10;  
  15.             res[i] = tmp;  
  16.         }  
  17.         StringBuilder sb = new StringBuilder();  
  18.         for (int num : res) sb.append(num);  
  19.         while (sb.length() != 0 && sb.charAt(0) == '0') sb.deleteCharAt(0);  
  20.         return sb.length() == 0 ? "0" : sb.toString();  
  21.     }  
  22. }  


原文链接http://blog.csdn.net/crazy__chen/article/details/45752001