大整数乘法
题干如下:
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. Note: The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly.
289*785为例:

代码如下:
class Solution {
public: string multiply(string num1, string num2) {
int s1 = num1.size(); int s2 = num2.size(); if(num1 == "0" || num2 == "0")return "0"; int k = s1+s2-2; if(k <= 0){
} vector<int>v(s1+s2,0); for(int i = 0; i<s1;i++) //未进位 for(int j = 0;j<s2;j++){
v[k-i-j]+=(num1[i]-'0')*(num2[j]-'0'); } int carry = 0; for(int i = 0;i<s1+s2;i++){
//进位 v[i]+=carry; carry = v[i]/10; v[i] = v[i]%10; } reverse(v.begin(),v.end()); int u = 0; while(v[u] == 0)u++; //去掉前面的0 string res = ""; for(int i = u;i<v.size();i++) res+=v[i]+'0'; return res; } };
下面更新一个Java版本的:
class Solution {
public String multiply(String num1, String num2) {
int len1 = num1.length(); int len2 = num2.length(); int[] res = new int[len1+len2]; int bit = 0; for(int i = len1-1; i>=0; i--){
for(int j = len2-1; j>=0; j--){
int ret = (num1.charAt(i)-'0') * (num2.charAt(j)-'0') + res[i+j+1]; res[i+j] += ret / 10; res[i+j+1] = ret % 10; } } boolean flag = true; // 去除前导0 StringBuilder sb = new StringBuilder(); for(int i = 0; i<res.length; i++){
if(res[i] == 0 && flag){
continue; }else{
flag = false; sb.append(res[i]); } } return sb.length() == 0 ? "0" : sb.toString(); } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/231025.html原文链接:https://javaforall.net
