0

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
    }

}
3
  • Please add a complete problem statement to your question. What is this method supposed to be doing? What is the sample input and output? Commented May 4, 2019 at 15:55
  • Does the length of both the array same? What happens if input is {9}, {9}? Can array have 2 digit or 3 digit number? Commented May 4, 2019 at 16:01
  • @SMA I firstly just looking for the base case in which the parsed in numbers are Integers from 0 to 9. Extension maybe come later. But what I'm looking forward is the {9}, {9} case. Do you have any suggestions for improvement? Commented May 4, 2019 at 16:40

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That's really a good case to use streams! Can you tell something more about how the .mapToObject() function works? Maybe you can say something about the signature IntFunction<? extends U> mapperI do not really understand what happens there..
Sure. Here in the mapToObj(...) we convert each element from an int to a String using the valueOf method. Next, we collect each of these individual Strings into one String by means of Collectors.joining(...). Now, we convert this String into a long. You can read up more about streams from the docs here. Edited the answer to reflect the same.
That's awesome! Big thanks! One question left - Can you furthermore tell me how to read the quoted signature of the .mapToObj()-function ? What is IntFunction? Does it mean, that a function has to return an IntValue or how is a IntFunction defined? What is U? What is the mapper?
It is hard to explain these concepts via comments. 1. IntFunction is a functional interface. 2. U is used to denote the use of generics. 3. mapper is the name of the reference of the generic type U. I suggest you to try and read up more of these topics to get a better understanding.
2

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.

2 Comments

I would like to use the Integer.parseInt() Option, but the problem is, that if I'm going to execute System.out.println(Integer.parseInt(result.toString())); The console prints out: Exception in thread "main" java.lang.NumberFormatException: For input string: "[I@7852e922" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at dAbgabe.Addition.main(Addition.java:47)
@Twixx you can not use Array.toString() you have to generate the String yourself. I added it to my answer. Alternatively look at Nicholas K's Answer he used is using a Stream and a long result.
1
    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

Comments

1

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)

Comments

0

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);
        }

    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.