我在尝试添加两个"大整数"时遇到了问题。字节数组一起以相反的顺序存储以帮助数学。这是我的构造函数。
public class Intzilla {
public byte[] digits;
//private byte negative = -1;
private byte zero = 0;
private byte positive = 1;
private byte posNegZero = 0;
private boolean negative;
private String inputString;
public Intzilla() {
this("0");
}
public Intzilla(String s) {
String tempString = s;
inputString = s;
tempString = tempString.trim();
if(tempString.substring(0,1).equals("-")){
negative = true;
tempString = tempString.substring(1);
} else if(tempString.substring(0,1).equals("+")){
negative = false;
tempString = tempString.substring(1);
}else {
negative = false;
}
while((tempString.substring(0,1).equals("0")) && (tempString.length() > 1)){
tempString = tempString.substring(1);
}
digits = new byte[tempString.length()];
for(int i = 0; i < tempString.length(); i++){
String currentChar = tempString.substring(i, i+1);
byte tempDigits = Byte.parseByte(currentChar);
digits[(digits.length - 1) -i] = tempDigits;
}
}
到目前为止,这是我尝试过的plus方法。获得&#34;可能有损转换从转换为字节&#34;。
public Intzilla plus(Intzilla addend) {
byte carry = 0;
byte mod = 10;
Intzilla result = new Intzilla();
for(int i = 0; i <= addend.digits.length-1; i++) {
result.digits[i] = (byte)(this.digits[i] + addend.digits[i] + carry)% mod;
carry = (byte)(this.digits[i] + addend.digits[i] + carry) / 10;
}
return result;
}
答案 0 :(得分:0)
此格式有效
byte [] newbytes = new byte [20];
byte [] oldbytes = new byte [20];
for (int x = 0; x < oldbytes.length; x++) {
newbytes [x] = (byte) ((newbytes[x] + oldbytes [x]) / 100);
}