[leetcode] Multiply Strings

來源:互聯網
上載者:User

標籤:class   blog   code   java   http   tar   

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.

https://oj.leetcode.com/problems/multiply-strings/

思路:大數乘法,類比筆算過程即可。

注意的細節:

  1. 前置0去掉;
  2. 結果為0;

 

代碼:

import java.util.Arrays;public class Solution {public String multiply(String num1, String num2) {if (num1 == null || num2 == null || num1.length() == 0|| num2.length() == 0)return null;int n1 = num1.length();int n2 = num2.length();char[] str1 = num1.toCharArray();char[] str2 = num2.toCharArray();char[] prod = new char[n1 + n2];Arrays.fill(prod, ‘0‘);int i, j;for (i = 0; i < n1; i++)for (j = 0; j < n2; j++) {prod[i + j] = (char) ((prod[i + j] - ‘0‘)+ (str1[n1 - 1 - i] - ‘0‘) * (str2[n2 - 1 - j] - ‘0‘) + ‘0‘);}int c = 0;for (i = 0; i < n1 + n2; i++) {prod[i] = (char) ((prod[i] - ‘0‘) + c + ‘0‘);if (prod[i] - ‘0‘ + c > 9) {c = (prod[i] - ‘0‘) / 10;prod[i] = (char) ((prod[i] - ‘0‘) % 10 + ‘0‘);} elsec = 0;}StringBuilder sb = new StringBuilder();i = n1 + n2 - 1;while (i >= 0 && prod[i] == ‘0‘)i--;if (i == -1) {sb.append("0");return sb.toString();}for (; i >= 0; i--) {sb.append(prod[i]);}return sb.toString();}public static void main(String[] args) {System.out.println(new Solution().multiply("123", "12345"));System.out.println(new Solution().multiply("0", "123"));}}

 

 

 

參考:

http://www.cnblogs.com/TenosDoIt/p/3735309.html

http://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/comment-page-1/#comment-122

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.