【数据结构和算法】反转数字,图文详解
反转数字
http://www.nowcoder.com/questionTerminal/1a3de8b83d12437aa05694b90e02f47a
1,翻转每一位数字即可,原理比较简单,我们直接来看图分析
public int reverse(int x) {
int res = 0;
while (x != 0) {
int t = x % 10;
int newRes = res * 10 + t;
//如果数字溢出,直接返回0
if ((newRes - t) / 10 != res)
return 0;
res = newRes;
x = x / 10;
}
return res;
}
2,实际上我们还可以改的更简洁一下
public int reverse(int x) {
long res = 0;
while (x != 0) {
res = res * 10 + x % 10;
x /= 10;
}
return (int) res == res ? (int) res : 0;
}
如果觉得有用就给个赞吧,还可以关注我的《牛客博客》查看更多的详细题解
数据结构和算法 文章被收录于专栏
专注于算法题的讲解,包含常见数据结构,排序,查找,动态规划,回溯算法,贪心算法,双指针,BFS和DFS等等。