码迷,mamicode.com
首页 > 编程语言 > 详细

Java [Leetcode 43]Multiply Strings

时间:2015-12-07 22:31:02      阅读:217      评论: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.

解题思路:

设置数组记录单个位置相乘的结果,最后负责相加进位。

代码如下:

public class Solution {
    public String multiply(String num1, String num2) {
		int num1Length = num1.length();
		int num2Length = num2.length();
		int d1, d2;
		int carry = 0;
		int temp;
		int[] caculate = new int[num1Length + num2Length];
		StringBuilder sb = new StringBuilder();

		for (int i = num1.length() - 1; i >= 0; i--) {
			d1 = num1.charAt(i) - ‘0‘;
			for (int j = num2.length() - 1; j >= 0; j--) {
				d2 = num2.charAt(j) - ‘0‘;
				caculate[i + j + 1] += d1 * d2;
			}
		}

		for (int i = caculate.length - 1; i >= 0; i--) {
			temp = (caculate[i] + carry) % 10;
			carry = (caculate[i] + carry) / 10;
			caculate[i] = temp;
		}

		for (int num : caculate)
			sb.append(num);

		while (sb.length() > 1 && sb.charAt(0) == ‘0‘) {
				sb.deleteCharAt(0);
		}

		return sb.toString();

	}
}

  

 

Java [Leetcode 43]Multiply Strings

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/5027514.html

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