0
Swap first and last digits of a number
eg . 1234 4231
2 Respostas
+ 1
if you have int 1234 converted to String "1234",
it is easy swap first and last character
and convert "4231" to int
if you need math. solution of length
int length = (int) (Math.log10(n)+1);
or you can divide with 10 in loop
for first, (int) conversion is necessary
int y = n / (int) Math.pow(10, length-1);
0
Integer.toString gives you the length of your number.
n % 10 -> last digit
n / 10^length - 1 -> first digit
In your case:
length = 4;
int first = 1;
int last = 4;
n -= first * (10^length-1);
//1234 - 1000 = 234
n += last * (10^length-1);
//234 + 4000 = 4234
n -= last;
//4234 - 4 = 4230
n += first;
//4230 + 1 = 4231
10^... -> you can use Math.pow(10, length - 1);