Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate an array of number into one number

I'm trying to take an array of any length of ints, and concatenate it into a single number without adding it up. For instance, if I have an array that goes as follows

[ 1, 7, 12, 16, 3, 8]

I want to have a variable that will equal 17121638, not equal 47.

I'm supposed to take a input of string and change it into an int without using Interger.parseInt() on the whole input itself.

This is my current attempt:

public static String toNum(String input) {
    String [] charArray = new String [input.length()];
    int [] parsedInput = new int [input.length()];
    for(int i; i < input.length(); i++){
        charArray[i] = input.substring(i);          
    }
    for(int c; c < charArray.length; c++){
        parsedInput[c] = Integer.parseInt(charArray[c]);            
    }
like image 331
user2748943 Avatar asked Jan 26 '26 22:01

user2748943


1 Answers

Try this:

int[] nums = { 1, 7, 12, 16, 3, 8 };

StringBuilder strBigNum = new StringBuilder();
for (int n : nums)
    strBigNum.append(n);

long bigNum = 0;
long factor = 1;
for (int i = strBigNum.length()-1; i >= 0; i--) {
    bigNum += Character.digit(strBigNum.charAt(i), 10) * factor;
    factor *= 10;
}

Now the bigNum variable contains the value 17121638; in this case it was easier to work with strings. Be careful, if the input array is too big (or the numbers are too big) the resulting value won't fit in a long.

like image 88
Óscar López Avatar answered Jan 29 '26 11:01

Óscar López