leetcode--Multiply Strings

本文提供了一种解决两个大数相乘问题的有效方法,并通过Java代码实现了这一算法。该算法能够处理任意大的非负整数,将输入的字符串形式的大数转换为字符数组进行逐位相乘,最后把结果转换回字符串形式返回。

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.youkuaiyun.com/crazy__chen/article/details/45752001

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值