大数相乘(java)

mport java.util.Scanner;
02  
03 public class Multiply
04 {
05     public String mul(String str1,String str2)
06     {
07         StringBuffer bstr=new StringBuffer();
08         int i=0,j=0;
09         for(i=0;i<str1.length()+str2.length();i++)
10         {
11             bstr.append('0');
12         }
13         int k=bstr.length()-1,add=0,temp=0;
14         for(j=str2.length()-1;j>=0;j--)
15         {
16             if(str2.charAt(j)!='0')
17             {
18                 for(i=str1.length()-1;i>=0;i--)
19                 {
20                     k=i+j+1;
21                     temp=(str2.charAt(j)-'0')*(str1.charAt(i)-'0')+(bstr.charAt(k)-'0');
22                     bstr.setCharAt(k--, (char)('0'+temp%10));
23                     add=temp/10;
24                     while(add!=0)
25                     {
26                         temp=add+bstr.charAt(k)-'0';
27                         bstr.setCharAt(k--, (char)('0'+temp%10));
28                         add=temp/10;
29                     }
30                 }
31             }
32         }
33         return bstr.substring(firstNotZeroIndex(bstr));
34     }
35      
36     private int firstNotZeroIndex(StringBuffer str)
37     {
38         for(int i=0;i<str.length();i++)
39             if(str.charAt(i)!='0')
40                 return i;
41         return str.length()-1;
42     }
43      
44     public static void main(String[] args)
45     {
46         Multiply mul=new Multiply();
47         Scanner cin=new Scanner(System.in);
48         System.out.print("请输入第一个整数:");
49         String str1=cin.next();
50         System.out.print("请输入第二个整数:");
51         String str2=cin.next();
52         System.out.print("结果是:");
53         System.out.println(mul.mul(str1, str2));
54     }
55 }  

你可能感兴趣的:(大数相乘(java))