/*
**
BigIntegerDemo.java
2012-11-10
**
**/
import java.util.*;
class BigInteger {
int[] num;
int len;
//构造函数,把字符串转化为整型数组
BigInteger(String str){
this.len = str.length();
num = new int[str.length()];
for(int i = 0 ; i < str.length() ; i++ )
num[i] = Integer.parseInt((String.valueOf(str.charAt(i))));
}
//打印函数
void print() {
if(this.num[0] != 0)
System.out.print(this.num[0]);
for(int i = 1 ; i < this.len ; i++){
System.out.print(this.num[i]);
}
System.out.println();
}
//把整形数组转化为字符串的函数
String toString(int[] result) {
String trans = "";
for(int i = 0 ; i < result.length ; i++) {
trans += result[i]+"";
}
return trans;
}
//大数加法
BigInteger add(BigInteger num2) {
int len1 = this.num.length;
int len2 = num2.num.length;
int max_len = (len1 > len2)? len1 : len2 ;
int[] add_result = new int[max_len + 1];
int i , j , k , temp;
for(i = len1 - 1 , j = len2 - 1 , k = max_len ; i >= 0 && j >= 0 ; i-- , j -- , k--){
add_result[k] += this.num[i] + num2.num[j];
temp = add_result[k] / 10;
if(temp > 0){
add_result[k-1] += temp;
add_result[k] = add_result[k] % 10;
}
}
if(max_len == len1){
for(;k > 0 && i >= 0 ; k-- , i--){
add_result[k] += this.num[i];
temp = add_result[k] / 10;
if(temp > 0){
add_result[k-1] += temp;
add_result[k] = add_result[k] % 10;
}
}
}
else{
for(;k > 0 && j >= 0; k-- , j--){
add_result[k] += num2.num[j];
temp = add_result[k] / 10;
if(temp > 0){
add_result[k-1] += temp;
add_result[k] = add_result[k] % 10;
}
}
}
String trans = toString(add_result);
return new BigInteger(trans);
}
//大数乘法
BigInteger multiply(BigInteger num2) {
int len1 = this.num.length;
int len2 = num2.num.length;
int[] multiply_result = new int[len1+len2];
int i , j , k , r , temp;
for(i = len2 - 1 , r = len1 + len2 - 1 ; i >= 0 ; i-- , r--)
for(j = len1 - 1 , k = r ; j >= 0 ; j-- , k--){
multiply_result[k] += this.num[j]*num2.num[i];
temp = multiply_result[k] / 10;
if(temp > 0){
multiply_result[k-1] += temp;
multiply_result[k] = multiply_result[k] % 10;
}
}
String trans = toString(multiply_result);
return new BigInteger(trans);
}
}
class BigIntegerDemo{
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
String str1, str2;
System.out.println("Input the First BigInteger:");
str1 = sc.next();
System.out.println("Input the Second BigInteger:");
str2 = sc.next();
BigInteger biginteger1 = new BigInteger(str1);
BigInteger biginteger2 = new BigInteger(str2);
System.out.print(str1 + "+" + str2 + "=");
biginteger1.add(biginteger2).print();
System.out.print(str1 + "*" + str2 + "=");
biginteger1.multiply(biginteger2).print();
System.out.println("继续计算?(Y/N)");
String judge = sc.next();
if(judge.equalsIgnoreCase("y"))
continue;
else
break;
}
}
}
自己写的大数类 目前只实现了正数的加法和乘法 而且貌似算法非常麻烦 先贴上来 日后改进..
Java 大数类 目前仅实现正数的加法和乘法
最新推荐文章于 2023-01-29 10:35:46 发布