简体   繁体   中英

Recursion and Immutability

I'm having the hardest time trying to get my class to work properly. It's a natural number class with methods like increase and decrease. I'm trying to make it immutable, and I'm stuck. If I increment a number such that it's least significant digit isn't 9, it works fine. But once I get to the boundary case, it fails.

IE. I have a number that's 69999, I increment it and it's 7.

private SlowBigNatural(int[] natural, int nSize){
    this.nSize = nSize - 1;
    this.natural = new int[this.nSize];
    for (int i = 0; i < this.nSize; i++) {
        this.natural[i] = natural[i];
    } 
}
@Override
public BigNatural increment() {
    int[] nClone = natural.clone();
    if (nSize == 1 || nClone[nSize - 1] != HIGHEST) {
        nClone[nSize - 1]++;
        String nString = "";
        for(int i = 0; i < nSize; i++){
            nString += String.valueOf(nClone[i]);
        }
        BigNatural nInc = new SlowBigNatural(nString);
        return nInc;
    } 

    else {
        nClone[nSize - 1] = 0;
        BigNatural temp = new SlowBigNatural(nClone, nSize);
        return temp.increment();
    }
}

I'm a little confused as to the endianness of your BigNatural. You don't explicitly mention how you're storing your number. You can either store with the most significant digit first, or least significant digit first.

That is the number 12,345 can be stored as {1,2,3,4,5} (Big Endian) or {5,4,3,2,1} (Little Endian).

If your increment is correct then getting 7 from adding 1 to 69,999 is likely a problem with endianness.

That is {7,0,0,0,0} is 70,000 if Big Endian or 7 if Little Endian. Check the string constructor. See what endianness it expects.

The problem is in the else . You have to compose the number after increment:

else {
        nClone[nSize - 1] = 0;
        BigNatural temp = new SlowBigNatural(nClone, nSize);
        BigNatural incremented = temp.increment();

        return new SlowBigNatural(addElement(incremented.natural, 0), nSize + 1);
    }



private int[] addElement(int[] arr, int element) {
      int[] copy = new int[arr.length+1];
      for (int index = 0; index < arr.length+1; index++){
            copy[index] = arr[index-1];
      }
      copy[arr.length] = element;
      return copy;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM