尝试添加2个数组时额外的0位数

时间:2012-03-25 20:19:14

标签: java

我正在开发一个程序,需要在不使用java中的biginteger类的情况下计算2个大整数的总和。我被困在我的for循环中,它计算总和。我得到额外的0所以30 + 30 = 600。

我很确定这是因为我以错误的方式遍历数组。我需要采取相反的方式(从右侧开始,就像添加数字时那样)但是我似乎无法修复它而不会出现数组索引错误。

这是我的代码:

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循环更改为以下内容:

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

2 个答案:

答案 0 :(得分:1)

您的添加代码假定最低有效数字位于array[0],但您的阅读代码会将最高位数放在那里。你应该在阅读后反转数组。

答案 1 :(得分: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
}
}

更新回复评论: 我也在上面编辑,调用此函数来填充堆栈。

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
 }