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]);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With