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 <=
.
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 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.
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;
}
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) */
}
}
Convert an integer to an array of digits C++
If what you really want is just to get the resulting vector, you can do this with math instead of converting things to strings
std::vector<int> plusOne(const std::vector<int>& digits) {
std::vector<int> res = digits;
res[res.size()-1] += 1;
// carry the 1 if any digit is > 9
int p = res.size()-1;
while (res[p] > 9) {
res[p] = res[p] % 10;
if (p > 0) {
res[p - 1] += 1;
--p;
}
else {
res.insert(res.begin(), 1);
}
}
return res;
}
You can try it out and see that it works, make sure to test with a number where the result has more digits than the input.
void print(const std::string& name, const std::vector<int>& v) {
std::cout << name << " = ";
for (auto&& vi : v) std::cout << vi << " ";
std::cout << std::endl;
}
int main() {
std::vector<int> in = { 1,2,9 };
auto out = plusOne(in);
print("in",in);
print("out",out);
in = {9,9 };
out = plusOne(in);
print("in",in);
print("out",out);
return 0;
}
Produces this result:
in = 1 2 9
out = 1 3 0
in = 9 9
out = 1 0 0
If you really want to do it with strings for some reason, this will accomplish the same thing, but keep in mind that this will fail for large numbers of digits (for numbers greater than INT_MAX numB
will overflow)
std::vector<int> plusOne(const std::vector<int>& digits) {
std::vector<int> res;
std::stringstream ss;
for (int i : digits) {
ss << i;
}
int numB;
ss >> numB;
numB++;
std::string numstr = std::to_string(numB);
for (int i = 0; i < numstr.size(); ++i) {
std::string c = numstr.substr(i, 1);
res.push_back(std::atoi(c.c_str()));
}
return res;
}
Related Topics
Java for Loop Syntax: "For (T Obj:Objects)"
Show Jframe in a Specific Screen in Dual Monitor Configuration
Assert Equals Between 2 Lists in Junit
Get the Index of a Pattern in a String Using Regex
Java Regex Replace with Capturing Group
Java - Best Way to Grab All Strings Between Two Strings? (Regex)
Java: "Final" System.Out, System.In and System.Err
How to Replace a Character in a String in Java
Jdk9: an Illegal Reflective Access Operation Has Occurred. Org.Python.Core.Pysystemstate
Jax-Rs - How to Return JSON and Http Status Code Together
Why Does This Go into an Infinite Loop
Difference Between List, List<>, List<T>, List<E>, and List<Object>
Is the Buildsessionfactory() Configuration Method Deprecated in Hibernate
Building Executable Jar with Maven
Difference in System. Exit(0) , System.Exit(-1), System.Exit(1 ) in Java