Ndrslmpk
Ndrslmpk

Reputation: 154

How to convert int array into int

Currently i started reading a book about alogirthms so I'm now trying some very simple algorithms to get comfortable with converting and so on.. In this small class I want to enable a school adding function with carry.

How can i convert the resulting Int Array into an int? I do not know how to convert them adequate..

The current result is [7, 8, 3, 7, 9, 0, 5, 6] and I want to concat the numbers into one Integer of (78379056). Which possibilities do I have?

public class Addition {

    public int[] addiere(int[] a, int[] b) {
        int res = 0;
        int[] c = new int[a.length];
        for(int i = a.length-1 ; i>=0 ; i--) {
            res = a[i]+b[i];
            if(res>=10) {
                c[i] = oneValue(res);
                a[i-1]+=1;
            } else c[i]=res;
            System.out.println("a -- "+a[i]+"  b -- "+b[i]+"  c -- "+c[i]);
        }
        return c;
    }

    public int oneValue(int t) {
        String res;
        int val;
        res=Integer.toString(t);

        res = res.substring(res.length()-1);
        val = Integer.parseInt(res);

        return val;

    }


    public static void main(String[] args) {

        int[] a = {3,4,6,8,9,1,2,4};
        int[] b = {4,2,5,7,8,9,3,2};

        Addition add = new Addition();
        int[] result;

        //returns an array of Integers
        System.out.println(Arrays.toString(add.addiere(a, b)));

        result = add.addiere(a, b);

        //HERE should be a method to convert the result ( Array of Integers ) just into a normal integer
    }

}

Upvotes: 0

Views: 1205

Answers (5)

Jamailun
Jamailun

Reputation: 48

Eventually, you could multiply each number by a power of 10 and add them together. For example this code will return "1234".

int[] array = {1, 2, 3, 4};
int total = 0;
for(int i = 0; i < array.length; i++)
    if(array[i] > 9 && array[i] < 0)
        throw new IllegalArgumentException("Only use digits");
    else
        total += array[i] * Math.pow(10, array.length - i - 1);
System.out.println(total);

It works in all cases, except cases with number. Make sure you handle the error.

(be carrefull to Integer.MAX_VALUE)

Upvotes: 1

Nicholas K
Nicholas K

Reputation: 15423

Given the array

int arr[] = { 7, 8, 3, 7, 9, 0, 5, 6 };

you can simply do:

long num = Long.parseLong(Arrays.stream(arr)
                                .mapToObj(String::valueOf)
                                .collect(Collectors.joining()));

which outputs

78379056


Explanation:

  1. In the mapToObj(...) we convert each element from an int to a String using the valueOf method.
  2. Next, we collect each of these individual Strings into one String by means of Collectors.joining()
  3. Now, we convert this String into a long. You can read up more about streams from the docs here

We use long here just in case the number is too big to be contained in an int.

Upvotes: 3

gprasadr8
gprasadr8

Reputation: 879

You can use BigInteger to hold the number which is more than int max size as well as you can avoid NumberFormatException.

public static void main(String[] args) {
        int[] ary = {2,1,4,7,4,8,3,6,4,7};

        StringBuilder numBuilder = new StringBuilder();
        for(int num:ary) {
            numBuilder.append(num);
        }
        BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
        BigInteger finalNum = new BigInteger(numBuilder.toString());
        if(finalNum.compareTo(maxInt)>0) {
            //number is more the max size
            System.out.println("number is more than int max size");
        }else {
            int result = finalNum.intValueExact();
            System.out.println(result);
        }

    }

Upvotes: 0

Samuel Philipp
Samuel Philipp

Reputation: 11032

You can either convert the array into a String and use Integer.parseInt() to get this result or you use a simple loop adding up the numbers multiplied by 10 with their position exponent:

int r = 0;
for (int i = 0; i < result.length; i++) {
    r += result[i] * Math.pow(10, result.length - i - 1);
}

I would prefer this solution.

The result for the array [7, 8, 3, 7, 9, 0, 5, 6] is 78379056.

Beside that you should consider using long instead of int if you have numbers out of the int range (78379056).

Edit: Here is a solution with Integer.parseInt():

StringBuilder builder = new StringBuilder();
for (int i : result) {
    builder.append(i);
}
int r = Integer.parseInt(builder.toString());

Alternatively you can take a look at Nicholas K's answer.

Upvotes: 2

Matthew I.
Matthew I.

Reputation: 1803

    public static void main(String[] args) {
        int[] a =  {7, 8, 3, 7, 9, 0, 5, 6};


        int m = 1;
        int r = 0;

        for (int i=a.length-1; i>=0; i--) {
            r = a[i] * m + r;
            m = m * 10;
        }

        System.out.println(r);
    }

prints:

78379056

Upvotes: 1

Related Questions