我被告知我必須寫一個BigInteger類,我知道有一個,但我必須自己寫。我將採用整數或字符串,並將它們轉換爲數組來存儲它們。從那裏開始,我可以對這些數字進行加,減和乘。我已經把整數和字符串都做好了,並且讓數組很好。我有其他問題。BigInteger需要幫助的作業
對於添加,我試圖做一些檢查數字類型數組的大小,然後設置哪些越來越小。從那裏,我有它循環,直到它到達較小的一端,並且隨着它循環它將兩位數字的該部分的數字,並添加它們。現在可以,直到他們大於10歲,在這種情況下,我需要攜帶一個號碼。我想我也有這個工作。
請記住我的BigInt所具有的兩件事是數字的數組和一個int符號,1或-1。
所以在這種情況下,我有問題,它添加正確的符號是正確的。與減法相同。
至於乘法,我完全失去了,甚至沒有嘗試過。以下是我嘗試過的一些代碼:(add函數),請幫助我。
public BigInt add(BigInt val){
int[] bigger;
int[] smaller;
int[] dStore;
int carryOver = 0;
int tempSign = 1;
if(val.getSize() >= this.getSize()){
bigger = val.getData();
smaller = this.getData();
dStore = new int[val.getSize()+2];
if(val.getSign() == 1){
tempSign = 1;
}else{
tempSign = -1;
}
}else{
bigger = this.getData();
smaller = val.getData();
dStore = new int[this.getSize()+2];
if(this.getSign() == 1){
tempSign = 1;
}else{
tempSign = -1;
}
}
for(int i=0;i<smaller.length;i++){
if((bigger[i] < 0 && smaller[i] < 0) || (bigger[i] >= 0 && smaller[i] >= 0)){
dStore[i] = Math.abs(bigger[i]) + Math.abs(smaller[i]) + carryOver;
}else if((bigger[i] <= 0 || smaller[i] <= 0) && (bigger[i] > 0 || smaller[i] > 0)){
dStore[i] = bigger[i] + smaller[i];
dStore[i] = Math.abs(dStore[i]);
}
if(dStore[i] >= 10){
dStore[i] = dStore[i] - 10;
if(i == smaller.length - 1){
dStore[i+1] = 1;
}
carryOver = 1;
}else{
carryOver = 0;
}
}
for(int i = smaller.length;i<bigger.length;i++){
dStore[i] = bigger[i];
}
BigInt rVal = new BigInt(dStore);
rVal.setSign(tempSign);
return rVal;
對於所有三種操作(加法,減法和乘法),最簡單的實現方法是實現您在小學時用於在紙上執行這些操作的相同算法。祝你好運! – 2011-02-14 04:15:10
您是否向前或向後存儲值?您的添加算法似乎從左向右添加,除非您將數字保存爲反向,否則您使用的變體添加算法與您在小學時學到的算法略有不同,這是錯誤的。 – muddybruin 2011-02-14 04:33:52
我有相反的數組中的數字,是的。 – Tempus35 2011-02-14 04:35:22