题目描述:
Reverse digits of aninteger.
Example1: x = 123,return 321
Example2: x = -123,return -321
题目理解:
翻转一个整数的数字,整数的符号不变
题目分析:
1. 用10除取余数,得到个位数的数字;
2. 每次取得余数后计算得到新的数字(即翻转后的数字),原来的数字除以10去除已得到的个位数;
3. 翻转后得到的数字大小不能超过Integer的范围,对于超过范围的数返回0;
4. 翻转后得到的数字大小可能超过Integer的范围,因此用long存储。
题目解答:
public int reverse(Integer x) { long result = 0; int digit = 0; while (x != 0) { digit = x % 10; result = (result * 10 + digit); x /= 10; } if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){ return 0; } return (int)result; }