所以我一直在研究這個BigNum乘法方法(簡言之,方法需要一個BigNum其他方法,並且應該返回兩個大正整數的乘積而不使用bigint類)一段時間,而且我幾乎完成了然而,我仍然有問題附加零。我的幫助器方法似乎也沒有正確添加(例如,444 * 4應該返回爲「1776」,但它返回爲「161616」)。我需要有人來調試這個,並幫助我找出爲什麼它不是加工。任何幫助表示讚賞。有些人可以幫我弄清楚爲什麼我的零不會追加?
這裏的結果,當我嘗試做444 * 444爲例
預期的輸出應該是我得到:
1776
17760
177600
197136
實際輸出與我的代碼:
161616
1616160
1616160
3393936
我方法
/**Multiplies two <tt>BigNum<tt> values together and returns a new
*<tt>BigNum<tt> object with the resulting value.
*
*@param other object
*@returns a new BigNum with resulting value
*/
public BigNum mult(BigNum other) {
BigNum tmp = new BigNum();
BigNum acc = new BigNum();
String s="";
int count=0;
for(int i= 0; i < other.num.length() ; i++) { //each digit x of other
tmp = this.mult(Character.getNumericValue(other.num.charAt(i)));
if(i > 0) {
for(int j=0; j < i; j++) {
s = tmp.num + "0";
}
}else {
s = tmp.num;
}
tmp=new BigNum(s);
count++;
acc = acc.add(tmp);
}
return acc;
}
/**Helper method that adds the other value a set of number of times, 0-9
*
*@param and int n and other object
*@returns resulting value
*/
public BigNum mult(int n) {
String result;
int carry;
if(n==0){
result="0";
}
else{
carry =0;
result = "";
}
for(int i=this.num.length()-1; i >=0; i--){
int temp = n * Character.getNumericValue(this.num.charAt(i))
result=(temp%10) + result;
carry = temp/10;
if(carry > 0){
result = carry + result;
}
}
return new BigNum(result);
}
此代碼適用於更小的數字,但不適合較大的人(如果我做了類似1234567 * 9876543的事情就會中斷) – user4147933 2015-02-24 04:52:20
是的,我現在意識到這是因爲有人否定了答案。好的,您可以重寫將值保存在int []中,例如:444應該作爲新的int [] {4,4,4}存儲。那麼你的代碼會更清晰,更易於理解 – 2015-02-24 04:55:47