Leetcode——Reverse number

这个题其实逻辑不难,但是最坑爹的问题是如何判断整型数的溢出!!!

class Solution 
{
public:
	int reverse(int x) {
		if (INT_MIN == x) return 0;
		if (x < 0) return -reverse(-x);
		int result = 0;
		while (x > 0){
			int a = x % 10;
			x = x / 10;
			if ((INT_MAX - a) / 10 < result)    //判断溢出
				return 0;
			result = result * 10 + a;
		}
		return result;
	}
};

这里是怎么判断溢出的,我还没有弄明白。

时间: 2024-11-06 09:41:28

Leetcode——Reverse number的相关文章

LeetCode #Reverse Number#

刚背了单词,然后做个题玩玩-挑个软柿子踩踩-哈哈 很简单的思路.不过好玩的是我忘记检查处理完的数据是否符合整形数据返回了.因而好一会儿不能AC. 感谢 @Fantasy. 很快的指出我没有检查返回数据的范围. 先给出我超丑陋的解(python), 而后给出其他高手给出的很优雅的解!!也是用python 最后会给出利用java和C/C++的解. """ Programmer : EOF Date : 2015.03.31 File : reverse_interger.py &

Leetcode Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nod

LeetCode——Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also

[LeetCode] Palindrome Number [13]

题目 Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using

LeetCode: Reverse Nodes in k-Group [024]

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4648 Magic Pen 6 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others) Total Submission(s): 1857    Accepted Submission(s): 637 Problem Description In HIT, many people have

leetcode——Reverse Linked List II 选择链表中部分节点逆序(AC)

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ le

LeetCode: Reverse Linked List

LeetCode: Reverse Linked List Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the follo

Leetcode:Reverse Linked List II 反转链表区间

Reverse Linked List II Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given   1->2->3->4->5->NULL,  m = 2 and n = 4, return  1->4->3->2->5->NULL. Note:Given m, n satisfy the following

[leetcode]Valid Number @ Python

原题地址:http://oj.leetcode.com/problems/valid-number/ 题意:判断输入的字符串是否是合法的数. 解题思路:这题只能用确定有穷状态自动机(DFA)来写会比较优雅.本文参考了http://blog.csdn.net/kenden23/article/details/18696083里面的内容,在此致谢! 首先这个题有9种状态: 0初始无输入或者只有space的状态1输入了数字之后的状态2前面无数字,只输入了dot的状态3输入了符号状态4前面有数字和有do