Leetcode题解2:整数反转
2019-02-22 20:48
465 查看
题目
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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题解:
由题意我们可以得到,将一个输入的10进制整数反转,得到另一个十进制整数,如果末尾为0则去掉,如120变21,如果反转后32位整数溢出,那么返回0。
这里我们首先确定反转的算法:用一个数组存下每一个位,然后按照10进制整数的算法求出反转后32为整数的值。但是这里有一个问题,如何判断溢出呢?这里我们用一个64位的整数来保存反转后的值,如果它大于最大整数或者小于最小整数则返回0。
具体实现代码如下:
class Solution { public int reverse(int x) { if(x == 0) return 0; int[] digits = new int[15]; // 保存求出来的各位数字 int temp = x,i = 0; boolean sign = (x>0); // 用于判断符号 int t = temp%10; // 这里和下面一个while都是用于去除最后的0 while(t==0){ temp/=10; t=temp%10; } while(temp!=0){ // 得到保存的每一位的数字 t = temp%10; digits[i++]=t; temp /=10; } if(sign){ // 如果是正数 long ret = 0; int base = 10; for(int j = 0;j < i;j++){ // 迭代求出反转后的值 ret = ret*base+digits[j]; } if(ret <= Integer.MAX_VALUE){ return (int)ret; }else return 0; }else{ // 如果是负数 long ret = 0; int base = 10; for(int j = 0;j < i;j++){ ret = ret*base+digits[j]; } int minvalue = Integer.MIN_VALUE; if(ret >= minvalue){ return (int)ret; }else return 0; } } }
相关文章推荐
- LeetCode题解(python)-7. 整数反转
- leetcode 7 使用字符串操作反转整数
- 【LeetCode】 反转整数
- LeetCode 7 反转整数
- LeetCode7-整数反转
- (LeetCode)反转整数
- LeetCode题解(python)-8. 字符串转换整数
- [leetcode]反转整数
- LeetCode 7. Reverse Integer(整数反转)
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- LeetCode 题 -7. 整数反转
- Java&LeetCode 初入门——007. 整数反转
- leetcode 7. 整数反转(Java版)
- LeetCode 7. Reverse Integer 整数反转
- LeetCode-Python-7. 整数反转
- LeetCode第7题:整数反转 之 先从简单刚起(C++)
- LeetCode7.python实现:整数反转问题☆
- leetcode7. 整数反转
- LeetCode题解(python)-13. 罗马数字转整数
- leetcode的python实现 刷题笔记7: 反转整数