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

leetcode之Multiply Strings

时间:2015-05-14 21:59:58      阅读:104      评论: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 String multiply(String num1, String num2) {
	    BigInteger temp1 = new BigInteger(num1);
	    BigInteger temp2 = new BigInteger(num2);
	    BigInteger result = temp1.multiply(temp2);
	    return result.toString();
	      
	   }

  另外一种是实现:

public String multiply1(String num1, String num2) {
        if (num1 == null || num2 == null) {
            return null;
        }
        
        int len1 = num1.length(), len2 = num2.length();
        int len3 = len1 + len2;
        int i, j, product, carry;

        int[] num3 = new int[len3];
        for (i = len1 - 1; i >= 0; i--) {
            carry = 0;
            for (j = len2 - 1; j >= 0; j--) {
                product = carry + num3[i + j + 1] +
                    Character.getNumericValue(num1.charAt(i)) *
                    Character.getNumericValue(num2.charAt(j));
                num3[i + j + 1] = product % 10;
                carry = product / 10;
            }
            num3[i + j + 1] = carry;
        }

        StringBuilder sb = new StringBuilder();
        i = 0;

        while (i < len3 - 1 && num3[i] == 0) {
            i++;
        }

        while (i < len3) {
            sb.append(num3[i++]);
        }

        return sb.toString();
    }

  

leetcode之Multiply Strings

标签:

原文地址:http://www.cnblogs.com/gracyandjohn/p/4504538.html

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