2011-02-15 3 views
0

아래의 코드는 자바에서 내 자신의 BigInteger 클래스로 작성된 전체 코드입니다. 저는 이미있는 것을 사용하지만 교수는 이것을 원합니다.프로그래밍 도움말, 작동 방법

중요한 것은 BigInt를 만들어 데이터를 int []로 저장하고 양수는 1, 음수는 -1로 부호를 저장합니다. 거기에서 나는 물어볼 때 숫자를 더하거나 빼거나 곱하기를 원합니다. 이것은 전형적인 int, long 등의 typ 유형이라면 좋겠지 만 숫자가 배열에 있으므로 이러한 메소드에 대한 방법을 찾아야합니다.

나는 여러 가지 방법을 시도해 보았습니다. 두 숫자가 모두 양수이거나 음수 일 때 추가하는 것이 좋습니다. 그러나 혼합하면 혼란 스럽습니다. 내가 도움이 필요 무엇

는 각 유형의 작업을 수행하는 방법의 생각이 아니다, 나는 등 방법, 격자 곱셈을 알고 있지만, 나는이 물건을 할 것입니다 방법에 대한 psuedocode를 알아야합니다, 나는 완전히 손실입니다.

각 방법에 대해 비슷한 방법으로 여기 저기 물어 봤지만 아직 미안하지만 아직 며칠 만에 나올 예정입니다. 주말 내내 두뇌가 굳어졌습니다.

package BigInteger; 


public class BigInt{ 

    private int[] store; 
    private int sign; 

    public BigInt(){ 
     store = new int[10]; 
     sign = 1; 
    } 

    public BigInt(int[] data){ 
     store = data; 
    } 

    public BigInt(int data, int maxSize){ 
     int size = String.valueOf(data).length(); 
     if (maxSize == 0){ 
      store = new int[size]; 
     } 

     else if(size >= maxSize){ 
       store = new int[size]; 
      } 
     else{ 
       store = new int[maxSize]; 
      } 
     if (data > 0){ 
      sign = 1; 
     }else{ 
      sign = -1; 
     } 
     for(int i = 0; i < size; i++){ 
      store[i] = data % 10; 
      data = data/10; 
     } 
    } 

    public BigInt(String num){ 
     store = new int[num.length()]; 
     try{ 
      for(int i = 0; i < num.length();i++){ 
       store[i] = Integer.parseInt(num.substring(i,i+1)); 
      } 
     }catch(IndexOutOfBoundsException e){ 
       System.out.println("Index out of bounds"); 
      } 
    } 

    public BigInt add(BigInt val){ 
     int[] bigger; 
     int[] smaller; 
     int[] dStore; 

     //Compare sizes and set which is bigger in first and create a new int[] 
     if(val.getSize() >= this.getSize()){ 
      bigger = val.getData(); 
      smaller = this.getData(); 

      dStore = new int[val.getSize()+1]; 
     }else{ 

      bigger = this.getData(); 
      smaller = val.getData(); 

      dStore = new int[this.getSize()+1]; 
     } 


     //Loop through till the end of small and add cells 
     for(int i = 0;i<smaller.length;i++){ 
      if((this.getSign() == 1 && val.getSign() == 1) || (this.getSign() == -1 && val.getSign() == -1)){ 
       dStore[i] = Math.abs(bigger[i] + smaller[i]); 
      }else if((this.getSign() == -1 || val.getSign() == -1) && (this.getSign() == 1 || val.getSign() == 1)){ 
       if(this.getSign() < 0 && this.getSize() < val.getSize()){ 
        smaller = this.getData(); 
        bigger = val.getData(); 
        bigger[i] = bigger[i] + 10; 
       }else if(val.getSign() < 0 && val.getSize() < this.getSize()){ 
        smaller = val.getData(); 
        bigger = this.getData(); 
        bigger[i] = bigger[i] + 10; 
       } 
        dStore[i] = bigger[i] + smaller[i]; 
       } 
      } 

     for(int i=0;i<dStore.length;i++){ 
      if(dStore[i] >= 10){ 
       dStore[i] = dStore[i] % 10; 
       dStore[i+1] = dStore[i+1] + 1; 
      } 
     } 


     //Finish adding numbers after small is done 
     for(int i=smaller.length;i<bigger.length;i++){ 
      dStore[i] = Math.abs(bigger[i] + dStore[i]); 
     } 

     //Create new BigInt from int[] 
     BigInt rVal = new BigInt(dStore); 

     //Set sign of new BigInt 
     if(this.getSign() == 1 && val.getSign() == 1){ 
      rVal.setSign(1); 
     }else if(this.getSign() == -1 && val.getSign() == -1){ 
      rVal.setSign(-1); 
     }else if((this.getSign() == 1 && val.getSign() == -1) || (this.getSign() == -1 && val.getSign() == 1)){ 
      if(this.getSize() > val.getSize()){ 
       rVal.setSign(1); 
      }else{ 
       rVal.setSign(-1); 
      } 
     } 

     return rVal; 
    } 

    public BigInt subtract(BigInt val){ 
     int[] bigger; 
     int[] smaller; 
     int[] dStore; 
     int carryOver = 0; 

     //Compare sizes and set which is bigger in first and create a new int[] 
     if(val.getSize() >= this.getSize()){ 
      bigger = val.getData(); 
      smaller = this.getData(); 

      dStore = new int[val.getSize()+1]; 
     }else{ 

      bigger = this.getData(); 
      smaller = val.getData(); 

      dStore = new int[this.getSize()+1]; 
     } 

     //Loop through till the end of small and add cells 
     for(int i = 0; i < smaller.length;i++){ 
      dStore[i] = Math.abs(bigger[i] - smaller[i]); 
     } 

     for(int i=0;i<dStore.length;i++){ 
      if(dStore[i] >= 10){ 
       dStore[i] = dStore[i] % 10; 
       dStore[i+1] = dStore[i+1] + 1; 
      } 
     } 


     //Finish adding numbers after small is done 
     for(int i=smaller.length;i<bigger.length;i++){ 
      dStore[i] = Math.abs(bigger[i] + dStore[i]); 
     } 

     //Create new BigInt from int[] 
     BigInt rVal = new BigInt(dStore); 

     //Set sign of new BigInt 
     if(this.getSign() == 1 && val.getSign() == 1){ 
      rVal.setSign(1); 
     }else if(this.getSign() == -1 && val.getSign() == -1){ 
      rVal.setSign(-1); 
     }else if((this.getSign() == 1 && val.getSign() == -1) || (this.getSign() == -1 && val.getSign() == 1)){ 
      if(this.getSize() > val.getSize()){ 
       rVal.setSign(1); 
      }else{ 
       rVal.setSign(-1); 
      } 
     } 

     return rVal; 
    } 

    public int multiply(BigInt val){ 
     int[] bigger; 
     int[] smaller; 
     int[] dStore; 

     int[][] tempResult; 



     //Checks to see which is bigger and then adds that to bigger 
     if(val.getSize() >= this.getSize()){ 
      bigger = val.getData(); 
      smaller = this.getData(); 
      dStore = new int[val.getSize()+this.getSize()]; 
     }else{ 
      bigger = this.getData(); 
      smaller = val.getData(); 
      dStore = new int[val.getSize()+this.getSize()]; 
     } 

     tempResult = new int[smaller.length][bigger.length]; 
     String resultString = ""; 
     String[] tempStr = new String[smaller.length]; 
     int[] intResults = new int[smaller.length*bigger.length]; 
     int loop = 0; 

     //Makes one long string of the numbers 
     for(int i=smaller.length-1;i >= 0;i--){ 
      for(int j = bigger.length-1;j >= 0;j--){ 
       tempResult[i][j] = smaller[i] * bigger[j]; 
       resultString = new StringBuffer(resultString).insert(resultString.length(), tempResult[i][j]).toString(); 
      } 
     } 

     //Splits the string up into loop amount of strings smaller.length size 
     for(int i=0;i < resultString.length();i = i + smaller.length){ 
      tempStr[loop] = (resultString.substring(i - loop, (i + smaller.length))); 
      //System.out.println(tempStr[loop]); 
      loop++; 
     } 

     //Adds 0's to make a full matrix 
     for(int i = 0; i < loop;i++){ 
      while(tempStr[i].length() < tempStr[loop-1].length()){ 
       tempStr[i] = new StringBuffer(tempStr[i]).insert(tempStr[i].length(), "0").toString(); 
      } 
     } 

     int[] tempNum = new int[smaller.length]; 
     int[] finalNum = new int[bigger.length]; 

     for(int i=0;i<smaller.length;i++){ 
      tempNum[i] = tempNum[i] + (Integer.parseInt((tempStr[i].substring(0,tempStr[i].length()))) % 10); 
     } 
     for(int i =0; i < smaller.length;i++){ 
      finalNum[0] =+ tempNum[i]; 
     } 
     System.out.println(tempNum[1]); 



     //Makes a new string that has all the digits in equal length. 
     resultString = ""; 
     for(int i=0; i < smaller.length;i++){ 
      resultString = new StringBuffer(resultString).insert(resultString.length(), tempStr[i]).toString(); 
     } 

     for(int i = 0; i<resultString.length();i++){ 
      for(int j = 0; j < 1;j++){ 
       tempNum[j] = tempNum[j] + Integer.parseInt(resultString.substring(i,i+1)); 
       //System.out.println(tempNum[j]); 
      } 
     } 


     //System.out.println(resultString); 


     return 0; 
    } 


    public void reverse(){ 
     for (int left=0, right=this.store.length-1; left<right; left++, right--) { 
      int temp = store[left]; store[left] = store[right]; store[right] = temp; 
     } 
    } 

    public int getSize(){ 
     int size = this.store.length - 1; 
     return size; 
    } 

    public int[] getData(){ 
     return store; 
    } 

    public void displayData(){ 
     for(int i=0;i<this.store.length;i++){ 
      System.out.println(this.store[i]); 
     } 
     System.out.println("Sign: " + this.sign); 
    } 

    public int getSign(){ 
     return this.sign; 
    } 

    public void setSign(int tempSign){ 
     this.sign = tempSign; 
    } 

    public boolean isPositive(){ 
     return this.sign == 1; 
    } 

    public boolean isGreater(){ 
     return this. 
    } 
} 
+1

문제는 SO가 설계된 것 이상입니다. 나는 당신이 당신의 과정을위한 TA를 발견하고 그들과 함께가는 데 약간의 시간을 할애하기를 제안합니다. SO가 제공 할 수있는 것보다 많은 도움이 필요합니다. –

+0

좋은 생각,하지만 우리는 아무런 조교가 없었습니다. 최소한 제게는 교수님의 도움을받을 시간이 거의 없었습니다. 나는 수업과 일로 가득 찬 하루 종일을 보냈습니다. – Tempus35

+0

StackOverflow 사용 경험이 적으므로 설명이 도움이 될 수 있습니다. 사람들은 정답에 대해 감사해야하기 때문에 좋은 대답을 얻을 때 답변 옆의 위쪽 화살표를 눌러 "감사합니다."라고 말하십시오. 대답이 완전히 문제를 해결하고 가장 좋은 대답 인 경우 대답을 "수락"하십시오. 사람들은 당신이 "고맙습니다"라고 말하지 않거나 정답을 "받아 들일"수 없다는 것을 알게되고, 고마워하는 사람들은 감사하지 않은 사람을 돕는 데 시간을 낭비하기를 원하지 않습니다. –

답변

1

초등 학교 때와 마찬가지로 곱셈, 덧셈, 뺄셈 및 나누기에 대해 생각해 봐야합니다. 즉, 연필과 종이로 손으로 작업을 수행하는 방법에 대해 생각해 봐야합니다. 그런 다음 같은 방식으로 코드를 작성해야합니다. 중요한 부분은 이러한 작업을 동일한 방식으로 수행 할 때 BigInteger 버전이 제공하는 배열의 각 슬롯에 하나의 숫자를 저장해야한다는 것입니다.

코드를 작성하기 전에 문제를 해결하는 방법에 대한 명확한 아이디어가 있어야하며 솔루션과 일치하는 코드를 작성해야합니다.

최종 솔루션이 제공되었다고해도, 지금까지 제공 한 코드가 일반 Integer보다 큰 BigInteger를 구현하지 못하기 때문에 가능성을 이해하지 못했을 가능성이 매우 높습니다.

짐 개리슨은 TA와 이야기 할 것을 제안했으며, 나는 두 번째 권고안을 제시했습니다. 올바른 방법을 고르는 문제는 아닙니다. 교수가 물어 보는 과제를 잘못 이해하거나 Integer.MAX_INT보다 큰 수를 어떻게 표현할 수 있는지 오해합니다. 프로그램을 배우는 사람은 오해를 용납 할 수 있지만, 다른 사람에게 대답을 해 줄 것을 요청하면 장기적으로 심하게 다칠 것입니다.

다른 사람들이 당신을 위해 "어려운"부분을 수행하도록 요구함으로써 이해를 건너 뛰면 디플로마를 얻을 수 있지만, 어려운 인터뷰 질문을하는 사람은 종이 한 장만 가지고 있다는 것을 알게됩니다 "디플로마"가 아니라 컴퓨터에 대한 이해.

+0

자, TA가 없으므로 교수님의 출입이 제한됩니다. 많은 대학들이 더 좋은 자원을 가지고있는 것처럼 미안합니다. 네 잘못이 아니야. 각 자릿수가 개별적으로 처리되면 어떻게 할 것인지 생각한 다음 배열의 각 요소를 10 자리로 처리하십시오. 연필과 종이를 사용하여 손으로하는 것처럼 작업을하면 잘 할 수 있습니다. 행운을 빕니다. –