LeetCode #Reverse Number#

刚背了单词,然后做个题玩玩~挑个软柿子踩踩~哈哈

很简单的思路.不过好玩的是我忘记检查处理完的数据是否符合整形数据返回了.因而好一会儿不能AC.

感谢 @Fantasy. 很快的指出我没有检查返回数据的范围.

先给出我超丑陋的解(python), 而后给出其他高手给出的很优雅的解!!也是用python

最后会给出利用java和C/C++的解.

"""
Programmer : EOF
Date : 2015.03.31
File   :  reverse_interger.py
"""

class Solution:
    # @return an integer
    def reverse(self, x):
		buffer =[]

		INT_MAX = 0x7fffffff

		INT_MIN = (-INT_MAX - 1)

		if x > INT_MAX or x < INT_MIN :
		    return 0

		if x > 0 :
			tmp = x
			counter = 1
			while tmp > 0 :
				counter += 1
				buffer.append(tmp % 10);
				tmp /= 10

			tmp = 0
			for i in range(0, len(buffer)) :
				tmp *= 10
				tmp += buffer[i]

			if tmp > INT_MAX or tmp < INT_MIN :
				return 0

			return tmp

		elif x < 0 :
			tmp = -x
			counter = 1
			while tmp > 0 :
				counter += 1
				buffer.append(tmp % 10);
				tmp /= 10

			tmp = 0
			for i in range(0, len(buffer)) :
				tmp *= 10
				tmp += buffer[i]

			if tmp > INT_MAX or tmp < INT_MIN :
				return 0

			return -tmp

		else:
			return 0

#--------------------------just for testing ----------------------------

s = Solution()

print s.reverse(123)

... 确实好搓就很简单做一下很基础的数学运算,利用余数和商的特性,把结果保存在list中.而后逆序的组合成整数,最后别忘记重新检查整数是否符合要求,是否越界!!

下面给出别人很优雅的解:

class Solution:
  # @return an integer
  def reverse(self, x):
    if x<0:
      sign = -1
    else:
      sign = 1
    strx=str(abs(x))
    r = strx[::-1]
    return sign*int(r)

简直不能再短..帅的飞起

先强转成字符串,而后在利用python切片的技巧,逆序输出字符,然后再int()强转,限定好整数范围.

最后恢复数据的符号.

java解(来源于@凯旋冲锋):利用了内置整形的特性

package reverse_integer;

public class Solution {
	public int reverse(int x) {
		long r = 0;
		while (x != 0) {
			r = r * 10 + x % 10;
			x /= 10;
		}
		return r > Integer.MAX_VALUE || r < Integer.MIN_VALUE ? 0 : (int) r;
	}

	public static void main(String[] args) {
		System.out.println(new Solution().reverse(1563847412));
	}
}

最后献上皓神的解答,C语言实现.

自己抽自己一巴掌,擦,居然没看清楚皓神写的注释!!

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer,

// Source : https://oj.leetcode.com/problems/reverse-integer/
// Author : Hao Chen
// Date   : 2014-06-18

/**********************************************************************************
*
* Reverse digits of an integer.
*
* Example1: x =  123, return  321
* Example2: x = -123, return -321
*
*
* Have you thought about this?
*
* Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
*
* > If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
*
* > Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer,
*   then the reverse of 1000000003 overflows. How should you handle such cases?
*
* > Throw an exception? Good, but what if throwing an exception is not an option?
*   You would then have to re-design the function (ie, add an extra parameter).
*
*
**********************************************************************************/

#include <stdio.h>
#include <stdlib.h>

//Why need the INT_MIN be defined like that?
//Please take a look:
//  http://stackoverflow.com/questions/14695118/2147483648-0-returns-true-in-c
#define INT_MAX     2147483647
#define INT_MIN     (-INT_MAX - 1)
int reverse(int x) {
    int y=0;
    int n;
    while( x != 0){
        n = x%10;
        //Checking the over/underflow.
        //Actually, it should be y>(INT_MAX-n)/10, but n/10 is 0, so omit it.
        if (y > INT_MAX/10 || y < INT_MIN/10){
             return 0;
        }
        y = y*10 + n;
        x /= 10;
    }
    return y;
}

#define TEST(n, e)  printf("%12d  =>  %-12d    %s!\n",  n, reverse(n),  e == reverse(n)?"passed":"failed")

int main(int argc, char**argv)
{
    //basic cases
    TEST(  123,  321);
    TEST( -123, -321);
    TEST( -100,   -1);
    TEST( 1002, 2001);
    //big integer
    TEST( 1463847412,  2147483641);
    TEST(-2147447412, -2147447412);
    TEST( 2147447412,  2147447412);
    //overflow
    TEST( 1000000003, 0);
    TEST( 2147483647, 0);
    TEST(-2147483648, 0);
    //customized cases
    if (argc<2){
        return 0;
    }
    printf("\n");
    for (int i=1; i<argc; i++) {
        int n = atoi(argv[i]);
        printf("%12d  =>  %-12d    %s!\n",  n, reverse(n), reverse(reverse(n))==n ? "passed":"failed");
    }
    return 0;
}

时间: 2024-11-16 23:25:09

LeetCode #Reverse Number#的相关文章

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)    //判断溢出 retu

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