package com.jacking.num;
/**
* 利用数组结构实现大整数求和
* @author Jackig
* @date 2017-8-8
* @version Jacking所有,转载请说明出处
*/
public class BigIntegerByArray {
int[] a={};
int[] b={};
public BigIntegerByArray(String num1,String num2) {
super();
int num1len = num1.length();
int num2len = num2.length();
int[] num1s = new int[num1len];
int[] num2s = new int[num2len];
for(int i = num1len-1;i>=0;i--){
int index = (num1len-1)-i;
num1s[index] = Integer.valueOf(num1.charAt(i)+"");
}
for(int i = num2len-1;i>=0;i--){
int index = (num2len-1)-i;
num2s[index] = Integer.valueOf(num2.charAt(i)+"");
}
this.setA(num1s);
this.setB(num2s);
}
public int[] getA() {
return a;
}
public void setA(int[] a) {
this.a = a;
}
public int[] getB() {
return b;
}
public void setB(int[] b) {
this.b = b;
}
/**
* 求和
* @return
*/
public String sum(){
String result = "";
int alen = a.length;
int blen = b.length;
if(alen>=blen){
for(int i=0;i<b.length;i++){
int v = b[i]+a[i];
if(v>10){
a[i]=v%10;
int nexti=i+1;
a[nexti]=a[nexti]+1;
}else{
a[i]=v;
}
}
int len = a.length;
for(int i = 1;i<=len;i++){
result+=""+a[len-i];
}
}else{
for(int i=0;i<a.length;i++){
int v = b[i]+a[i];
if(v>=10){
b[i]=v%10;
int nexti=i+1;
b[nexti]=b[nexti]+1;
}else{
b[i]=v;
}
}
int len = b.length;
for(int i = 1;i<=len;i++){
result+=""+b[len-i];
}
}
return result;
}
public static void main(String[] args) {
String num1="1000000000000000000000000000000000000000";
String num2="10000000000000000000000000000000000000001";
System.out.println(new BigIntegerByArray(num1,num2).sum());
}
}
利用数组结构实现大整数求和
最新推荐文章于 2023-02-15 19:45:21 发布