TyroProgrammer February 2016

Having trouble getting each character from a string and add it to an ArrayList of integers sn:aware of bigInteger

I am having a hard time trying to come up with a constructor for this example using an array list.

public class BigIntConstructorDemo {
public static void main(String[] args) {


    BigInt1 b1 = new BigInt1("1000000");

    System.out.println("b1 is " + b1); 

  }
}

This is a class with an array called digits that holds a max of 40 digits. The constructor loops through the array....

public class BigInt1 {
public static final int MAX_DIGITS = 40;
private int [ ] digits = new int[MAX_DIGITS];

public BigInt1(String s){
    for (int i = 0; i < MAX_DIGITS; i++)
        digits [i] = 0;
    int i = 0;
    for(int j = s.length()-1; j >= 0; j--){
        digits[i] = s.charAt(j) - '0';
        i++;    
    }
  }
}

and then uses the toString method.

public String toString(){
    String s = "";


    for (i = 0; i < MAX_DIGITS;i++)

        s = digits[i] + s;


    if (s.equals(""))
        s = "0";
    return s;

I know I have to use a for loop, but i just can't seem to get the syntax right. Should I use the .add method that comes with the array list class? how could take a single character in a string and then put it into each element of an array list?

import java.util.ArrayList;

public class BigInt2{
private ArrayList <Integer> bigNum = new ArrayList<Integer>();

public BigInt() {

}

public BigInt(String s){

 for(int index = 0;index ? bigNum.size();index++){

    }

Answers


Diego Martinoia February 2016

Yes, use add.

This is your old code with an array:

for(int j = s.length()-1; j >= 0; j--){
        digits[i] = s.charAt(j) - '0';
        i++;    
    }

with an arrayList foreach you get:

for (char c: s.toCharArray()) {
  digits.add(c - '0');
}

note that the endianness (left to right or right to left) is switched in this case, if you want it the other way around simply loop as in your previous example over s.toCharArray() positions:

char[] chars = s.toCharArray();
for(int j = chars.length-1; j >= 0; j--){
        digits.add(chars[j] - '0');
    }

Post Status

Asked in February 2016
Viewed 1,734 times
Voted 7
Answered 1 times

Search




Leave an answer