Converting Integer into Array of Digits

Convert an integer to an array of digits

The immediate problem is due to you using <= temp.length() instead of < temp.length(). However, you can achieve this a lot more simply. Even if you use the string approach, you can use:

String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}

You need to make the same change to use < newGuess.length() when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]. The vast majority of for loops I write use < in the condition, rather than <=.

How to convert an integer into an array of digits

I'd go with

var arr = n.toString(10).replace(/\D/g, '0').split('').map(Number);

You can omit the replace if you are sure that n has no decimals.

Converting integer into array of digits

Just using something like this:

int n = 544; // your number (this value will Change so you might want a copy)
int i = 0; // the array index
char a[256]; // the array

while (n) { // loop till there's nothing left
a[i++] = n % 10; // assign the last digit
n /= 10; // "right shift" the number
}

Note that this will result in returning the numbers in reverse order. This can easily be changed by modifying the initial value of i as well as the increment/decrement based on how you'd like to determine to length of the value.


(Brett Hale) I hope the poster doesn't mind, but I thought I'd add a code snippet I use for this case, since it's not easy to correctly determine the number of decimal digits prior to conversion:

{
char *df = a, *dr = a + i - 1;
int j = i >> 1;

while (j--)
{
char di = *df, dj = *dr;
*df++ = dj, *dr-- = di; /* (exchange) */
}
}

Converting an integer to an array of digits

Off the top of my head:

int i = 123;
var digits = i.ToString().Select(t=>int.Parse(t.ToString())).ToArray();

Converting an integer into an int array in Java

Java 8 Stream API

int[] intArray = Arrays.stream(array).mapToInt(Integer::intValue).toArray();

Source : stackoverflow

How do I separate an integer into separate digits in an array in JavaScript?

Why not just do this?

var n =  123456789;
var digits = (""+n).split("");

convert an integer number into an array

This would work for numbers >= 0

#include <math.h>

char * convertNumberIntoArray(unsigned int number) {
int length = (int)floor(log10((float)number)) + 1;
char * arr = new char[length];
int i = 0;
do {
arr[i] = number % 10;
number /= 10;
i++;
} while (number != 0);
return arr;
}

EDIT: Just a little bit more C style but more cryptic.

#include <math.h>

char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}


Related Topics



Leave a reply



Submit