zoukankan      html  css  js  c++  java
  • Java [Leetcode 43]Multiply Strings

    题目描述:

    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();
    
    	}
    }
    

      

  • 相关阅读:
    IOS Xcode编译项目-报错“ld: library not found for -XX”
    ios中关键词weak,assign,copy.strong等的区别
    iOS 控件
    iOS图片处理
    iOS 音频
    C语言文件操作
    iOS 删除相册中照片--来自简书
    ios sourecTree
    ios音频处理
    编码格式简介
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5027514.html
Copyright © 2011-2022 走看看