I’m trying to make a random number to be a palindrome. For example, generated random number 1234 should become 12344321.
So I wrote this code:
int num = (int)((Math.random()*100000)+1);
int palindrome = num;
System.out.println(num);
while (num > 0)
{
palindrome = palindrome*10+num%10;
num = num/10;
}
System.out.println("Palindrome: " + palindrome);
Sometimes it works, and I get, for example, number 6540 and palindrome 65400456. But for some reason in most cases I get, for example, number 94229 and palindrome 833057657. Or number 82270 and palindrome -362927364.
Why is it happening? What’s wrong with this code and how to fix it?
Thank you!
This is due to integer overflow. An
intis 32 bits wide and is therefore limited to values between-2,147,483,648and2,147,483,647.Taking
94229as an example,9422992249modulo(1<<32)is833057657, which is what you’re getting.Change
ints tolongs, and that’ll increase the range of numbers your code will be able to handle (the range will, of course, remain limited).If you need to go even further,
BigInteger(or strings) may be the answer.