2012-03-25 2 views
0

자바에서 biginteger 클래스를 사용하지 않고 2 개의 큰 정수의 합을 계산해야하는 프로그램을 작성 중입니다. 내가 내 합계를 계산 루프에 붙어 있어요. 나는 여분의 0을 얻고 있습니다. 30 + 30 = 600입니다.2 개의 배열을 추가 할 때 여분의 0 자리가

잘못된 방법으로 배열을 반복하고 있기 때문에 꽤 확신합니다. 반대 방향으로 가야합니다 (숫자를 추가 할 때처럼 오른쪽에서 시작).하지만 배열 색인 오류가 발생하지 않으면 문제를 해결할 수 없습니다. 여기

내 코드입니다 :

main: 

import java.util.Scanner; 

public class testLargeInteger 
{ 



public static void main(String[] args) 
    { 
    Scanner input = new Scanner(System.in); 
     String string1; 
     String string2; 
     int exp =0; 


     System.out.print("Enter the first integer: "); 
     //Store up the input string “string1” entered by the user from the keyboard. 
     string1 = input.next(); 

     LargeInteger firstInt = new LargeInteger(string1); 

     System.out.print("Enter the second integer: "); 
     string2 = input.next(); 
     //Store up the input string “string2” entered by the user from the keyboard. 
     LargeInteger secondInt = new LargeInteger(string2); 

     System.out.print("Enter the exponential integer: "); 
     //Store up the input integer “exp” entered by the user from the keyboard. 
     exp = input.nextInt(); 


     LargeInteger sum = firstInt.add(secondInt); 

     System.out.printf ("First integer: %s \n", firstInt.display()); 
     System.out.println("Second integer: " + secondInt.display()); 
     System.out.println(" Exponent: " + exp); 

     System.out.printf (" Sum = %s \n", sum.display()); 

    } 
} 

대형 정수 :

public class LargeInteger { 


    private int[] intArray; 


    //convert the strings to array 
    public LargeInteger(String s) { 
     intArray = new int[s.length()]; 
     for (int i = 0; i < s.length(); i++) { 
      intArray[i] = Character.digit(s.charAt(i), 10); // in base 10 
     } 
    } 

    public LargeInteger(int[] array) { 
     intArray = array; 
    } 

    //display the strings 
    public String display() {   
      String result=""; 

      for (int i = 0; i < intArray.length; i++) {  
      result += intArray[i]; 
      } 
      return result.toString(); 
     } 

    //get first array 
    public int[] getIntArray() { 
      return intArray; 
     } 

    //ADD method to add 2 arrays together 
    public LargeInteger add(LargeInteger secondInt){ 

     int[] otherValues = secondInt.getIntArray(); 

     int maxIterations = Math.min(intArray.length, otherValues.length); 
     int currentResult; //to store result 
     int[] resultArray = new int[Math.max(intArray.length, otherValues.length) +1 ]; 

     int needToAdd = 0; //to store result should be added next step 

     for(int i = 0; i < maxIterations; i++) { 
      currentResult = intArray[i] + otherValues[i]; 
      resultArray[i] = currentResult % 10 + needToAdd; //if more than 9 its correct answer 
      needToAdd = currentResult/10; //this is what you need to add on next step 
     } 

     resultArray[Math.max(intArray.length, otherValues.length) ] = needToAdd; 

     return new LargeInteger(resultArray); 

    } 

} 

내가 변화하려 한 이런 일에 합의 루프 :

for(int i = maxIterations; i >= 0; i--) 
+2

투표의 여지가 남기십시오 : 검사를 통해 코드의 오류를 찾아내는 낯선 사람에게 질문하는 것은 생산성이 떨어집니다. 디버거 나 print 문을 사용하여 문제를 확인 (또는 적어도 격리) 한 다음보다 구체적인 질문으로 돌아 가야합니다 (10 줄 [테스트 케이스] (http : /sscce.org)). –

+1

Java의 배열은 0을 기준으로합니다. 배열의 유효한 인덱스는 [0, array.length - 1]입니다. – Jeffrey

+0

나는 정말로 오류를 발견하라고 요구하는 것으로 보지 못했다. 아마도 어쩌면 .. 나는 옳은 길을 가고 있는지, 그리고 내가 반대 방향으로 돌아갈 필요가 있는지 확실히 모르겠다. .. – Sackling

답변

1

for 루프는 문제 중 하나입니다.

1] 캐리를 제대로 추가하지 않습니다.

2] 여기서 스택이 배열보다 적합합니다.

스택이있는 경우 (메서드 내부에 코드 삽입) : 참고 : number.add (num2);

public class LargeInt{ 
    private String number; 
    public LargeInt(String num){ 
     this.number = num; 
    } 

    public String add(String num2){ 
    Stack<Integer> adder = toIntegerStack(this.number);//UPDATE 
    Stack<Integer> addend = toIntegerStack(num2);//UPDATE 
    Stack<Integer> result = new Stack<Integer>(); 

    int carry =0; 
    int tmp = 0; 

    while(!.adder.isEmpty && !addend.isEmpty()){ 
    tmp = adder.pop()+addend.pop()+carry; 
    if(tmp > 10){ 
    carry = tmp/10; 
    tmp%=10; 
    }else{ 
    carry=0; 
    } 
    result.push(tmp); 
    }//while 

    while(!adder.isEmpty){ 
    tmp = adder.pop()+carry; 
    if(tmp > 10){ 
    carry = tmp/10; 
    tmp%=10; 
    }else{ 
    carry=0; 
    } 
    result.push(tmp); 
    }//while 

    while(!addend.isEmpty){ 
    tmp = addend.pop()+carry; 
    if(tmp > 10){ 
    carry = tmp/10; 
    tmp%=10; 
    }else{ 
    carry=0; 
    } 
    result.push(tmp); 
}//while 

//beyond this point the result is your answer 
//here convert your stack to string before returning 
} 
} 

UPDATE는 COMMENT 답변을 : 을 나는 또한 스택을 채우기 위해이 함수를 호출하기 위해 위의 편집을하고있다.

private Stack<Integer> toIntegerStack(String n){ 
    Stack<Integer> stack = new Stack<Integer>(); 
    for(char c: n.toCharArray()) 
     stack.push(c-48);//ASCII 
    return stack; 
}//toStack(String) 
당신이 배열을 사용하여 주장하는 경우

, 당신은 당신의 배열과 동일한 패턴을 따라야합니다.

int indexA=0; 
int indexB=0; 
int[] result = new int[1+A.length>B.length?A.length:B.length]; 
int indexResult=result.length-1; 

while(indexA < A.length && indexB <B.length){//inside is same idea 
    tmp = A[indexA++] + B[indexB++] + carry; 
    //... do here as for stacks for tmp and carry 
    result[indexResult--]; 
} 

while(indexA < A.length){ 
    //do as in stack version 
} 

    while(indexB < B.length){ 
    //do as in stack version 
} 
+0

네, 단지 for 루프를 고치려고 한 후에 다른 문제가 생겼습니다. 나는 너의 첩배를보고있다. 나는 배열을 사용할 필요가 없다. 나는 그것들을 더 편하게 생각했다 (상상 해보자.) 나는 스택을 사용하는 모습을 좋아한다. 그리고 나는 이것을 알아야한다고 생각합니다. 그러나 덧셈과 덧셈은 어떻게 채워지겠습니까? – Sackling

+0

몇 가지 명확성을 위해 새 업데이트를 참조하십시오. add 메서드에 의해 두 번 호출되는 private 함수를 만들었습니다. – kasavbere

+0

몇 가지 질문이 있는데, 개인 기능이 어떻게 작동하는지 이해하지 못합니까? c-48은 무엇입니까? 나는 그런 것을 본 적이 없으며 그것이 우리 코스의 범위를 벗어나는 것을 두려워합니다. LargeInt는 이미 가지고있는 LargeInteger 클래스의 일부가되어야한다는 공용 클래스를 만들었습니다. – Sackling

1

귀하의 추가 코드 최하위 자리가 array[0] 인 것으로 가정하지만 독서 코드가 가장 큰 숫자 거기에 무시 무시한 숫자. 읽은 후에 배열을 반대로해야합니다.

+0

코드를 읽음으로써 내 디스플레이 방법을 의미합니까? – Sackling

+0

아니, 나는 생성자가'String'을 취하는 것을 의미했다. 문자열에서 숫자를 인덱스 0부터 배열로 옮깁니다. 코드를 추가 할 때 인덱스 0에서 더 높은 인덱스로 올림을 전파합니다. 숫자는 가장 중요한 숫자로 먼저 쓰여 지므로 함께 맞지 않습니다. –

+0

아 의미가 있습니다. 감사! – Sackling

관련 문제