[leetcode]43. Multiply Strings@Java

来源:互联网 发布:php 在线人数统计 编辑:程序博客网 时间:2024/06/07 00:30

这其实是一道大数相乘问题,类似的题目我之前的博客已经发过了,今天相当于复习一下吧


https://leetcode.com/problems/multiply-strings/#/description


Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.


package go.jacob.day721;/** * 43. Multiply Strings * @author Jacob * */public class Demo1 {/* * 大数相乘 * Runtime: 21 ms.Your runtime beats 99.95 % of java submissions. * 用空间换时间:如果有空间要求的话,可以不建立arr1和arr2数组,直接在计算的时间用num1.charAt(i)-'0'即可 */public String multiply(String num1, String num2) {if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0)return null;if(num1.equals("0")||num2.equals("0"))return "0";int len1 = num1.length(), len2 = num2.length();int[] arr1 = new int[len1], arr2 = new int[len2];// 首尾交换,便于计算for (int i = 0; i < len1; i++) {arr1[len1 - 1 - i] = num1.charAt(i) - '0';}for (int i = 0; i < len2; i++) {arr2[len2 - 1 - i] = num2.charAt(i) - '0';}// 两数相乘结果的长度介于len1*len2-1到len1*len2int[] res = new int[len1 + len2];for (int i = 0; i < len1; i++) {for (int j = 0; j < len2; j++) {res[i + j] += arr1[i] * arr2[j];}}for (int i = 0; i < len1 + len2; i++) {while (res[i] >9) {res[i + 1] += res[i] / 10;res[i] = res[i] % 10;}}StringBuilder ans=new StringBuilder();for (int i = len1 + len2-1; i >=0; i--) {ans.append(res[i]);}//如果第一个元素是0,去除return ans.charAt(0) == '0' && ans.length() != 1 ? ans.substring(1) : ans.toString();}}





原创粉丝点击