Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to array

I would like to convert an integer into an array, so that it looks like the following:

int number = 123456 ;
int array[7] ;

with the result:

array[0] = 1 
array[1] = 2
...
array[6] = 6
like image 771
kantor Avatar asked Dec 07 '09 16:12

kantor


People also ask

Can we convert int to array in Java?

Using the toArray() method − The toArray() method of the Set interface accepts an array, populates it with all the elements in the current set object and, returns it. using this method, you can convert a Set object to an array.

How do you convert an element to an array in numbers?

To convert all elements in an array to integer in JavaScript, w ecan use the array map method. const arrayOfNumbers = arrayOfStrings. map(Number);

Can integer array convert to ArrayList?

An array can be converted to an ArrayList using the following methods: Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.


2 Answers

Perhaps a better solution is to work backwards:

123456 % 10 = 6

123456 / 10 = 12345

12345 % 10 = 5

12345 / 10 = 1234

like image 190
Broam Avatar answered Oct 17 '22 14:10

Broam


just use modular arithmetic:

int array[6];
int number = 123456;
for (int i = 5; i >= 0; i--) {
    array[i] = number % 10;
    number /= 10;
}
like image 38
user224003 Avatar answered Oct 17 '22 15:10

user224003