大数乘法(Java)

import java.util.Scanner;

public class Hello {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

String s1,s2;

s1=sc.next();

s2=sc.next();

String s=mul(s1,s2);

System.out.println(s);

}

public static String mul(String num1,String num2) {

num1=reverseString(num1);

num2=reverseString(num2);

StringBuilder res=new StringBuilder();

int carry=0;   //carry表示进位

int N1=num1.length();

int N2=num2.length();

int i=0,p=0,q=0;

for(;i<(N1+N2-1);i++) 

{

int sum=0;

int i1=0;

for(;i1<N1;i1++)

{

int i2=0;

for(;i2<N2;i2++)

{

if((i1+i2)==i)

{

p=charToInt(num1.charAt(i1));

q=charToInt(num2.charAt(i2));

sum=sum+p*q;

}

}

}

int r=(sum+carry)%10;

carry=(sum+carry)/10;

res.append(r);

}

if(carry!=0)

res.append(carry);

return removeHeadZero(res.reverse().toString());

}

static String reverseString(String ori) {

StringBuilder reversed=new StringBuilder(ori);

    reversed.reverse();//字符反转

    return reversed.toString();

}

static int charToInt(char ch) {

int value=(int)ch-‘0’;

return value;

}

static String removeHeadZero(String str) {

StringBuilder s = new StringBuilder(str);

for (int i = 0; i<str.length()-1; i++) {

if(str.charAt(i)==’0′)

s.deleteCharAt(0);

else break;

}

return s.toString();

}

}

    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/weixin_42270390/article/details/80413384
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞