package Others;
public class TestBignum {
public static void main(String args[]) {
Print p = new Print();
Bignum a = new Bignum("123456");
Bignum b = new Bignum("123456");
Bignum c = a.add(b);
/*
for(int i = 0;i < c.length();i++) {
System.out.println((int)c.ch[i]);
}
*/
p.printBignum(c);
}
}
package Others;
public class Print {
void print(Object s) {
System.out.print(s + "");
}
void println(Object s) {
System.out.println(s + "");
}
public String toString() {
return "Ok";
}
void println() {
System.out.println();
}
void printBignum(Bignum a) {
for(int i = 0;i < a.length();i++) {
print(a.getChar(i) + " ");
}
println();
}
}
package Others;
public class Bignum {
//chInt接收字符串参数
private char[] chInt;
//ch接受chInt的字符
char[] ch;
Bignum(String s) {
chInt = s.toCharArray();
ch = new char[chInt.length];
for(int i = 0;i < chInt.length;i++) {
//把char类型看做int
ch[i] = (char)(chInt[i] - 48);
//System.out.println((int)ch[i]);
}
//chInt = null;
}
//返回ch的长度
int length() {
return ch.length;
}
//返回数组字符
int getChar(int i) {
//System.out.println((int)ch[i]);
return (int)ch[i];
}
//实现加法
Bignum add(Bignum b) {
int max = length() > b.length() ? length() : b.length();
boolean flag = false;
char[] plus = new char[max + 1];
plus[0] = ' ';
for(int i = max - 1;i >= 0;i--) {
plus[i + 1] = (char)(ch[i] + b.ch[i]);
//System.out.print((int)plus[i + 1] + " ");
if(flag) {
plus[i + 1] += 1;
}
if(plus[i + 1] >= 10) {
plus[i + 1] -= 10;
flag = true;
} else {
flag = false;
}
}
if(flag) {
plus[0] = 1;
}
/*
for(int i = 0;i < plus.length;i++) {
if(' ' != (int)plus[i])
System.out.print(" " + (int)plus[i]);
}
*/
String str = "";
for(int i = 0;i < plus.length;i++) {
if(' ' == plus[i]) {
continue;
}
str += plus[i];
}
char[] ch = str.toCharArray();
for(int i = 0;i < ch.length;i++) {
System.out.print((int)ch[i]);
}
return new Bignum(str);
//return new Bignum("123");
}
}
这三段代码是一个大数加法的运算,打印的结果十分的诡异,不知道错到哪了??望各位大牛指点一下
大数运算???java
------解决方案--------------------
把它改成 str += (int)plus[i];