Reverse Integer

本贴最后更新于 2594 天前,其中的信息可能已经斗转星移

题目描述

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321

Example 2:

Input: -123 Output: -321

Example 3:

Input: 120 Output: 21

Note:

Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

翻转整数,如果越界了就返回 0。

解题思路

转换成字符串,用 long 存储检查大小。

代码

class Solution { public int reverse(int x) { String tmp = String.valueOf(x); long ret = 0; for (int i = tmp.length()-1; i >= 0; i--) { if (i == 0 && tmp.charAt(i) == '-') { ret *= -1; } else if (i == 0 && tmp.charAt(i) == '+') { break; } else if (tmp.charAt(i) >= '0' && tmp.charAt(i) <= '9') { ret *= 10; ret = ret + tmp.charAt(i) - '0'; } else { return 0; } } if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) return 0; return (int)ret; } }
  • 算法
    430 引用 • 254 回帖 • 24 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...