7. Reverse Integer

原创 2018年04月16日 10:19:35

7Reverse Integer

题目描述

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.

分析

判断正负号:s=cmp(x,0)  #python2.7里,x>0返回1, x<0返回-1

倒序输出:for value in rang(10)[::-1]涉及的数字倒序输出;
    b = a[i:j:s]这种格式呢,i,j与上面的一样,但s表示步进,缺省为1,所以a[i:j:1]相当于a[i:j];
    当s>0时,i缺省时,默认为0. j缺省时,默认为len(a);(第len(a)个元素不存在,输出索引值为0~len(a)-1的数);
    当s<0时,i缺省时,默认为-1. j缺省时,默认为-len(a)-1;

    所以a[::-1]相当于 a[-1:-len(a)-1:-1],也就是从最后一个元素到第一个元素复制一遍。

完整代码

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        s=cmp(x,0)  #python2.7里,x>0返回1, x<0返回-1
        r=int(str(abs(x))[::-1])
        return s*r*(r<2**31) #if x.bit_length()<32 else 0

轻松玩转Windows7基础视频教程[肖哥]

-
  • 1970年01月01日 08:00

LeetCode7——Reverse Integer

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 大意 反转i...
  • booirror
  • booirror
  • 2015-01-26 11:21:12
  • 2872

7. Reverse Integer 反转int

7. Reverse Integer问题:反转int,当有负号时需要保留负号。解决思路:1、先将int类型转换为string,按照之前写过的string类型做好反转,再转为int类型。2、不做类型转换...
  • u010223431
  • u010223431
  • 2016-05-06 09:48:57
  • 2584

LeetCode 7 Reverse Integer(翻转整数)

翻译翻转一个整型数例1:x = 123, 返回 321 例2:x = -123, 返回 -321原文Reverse digits of an integer.Example1: x = 123, re...
  • NoMasp
  • NoMasp
  • 2015-09-23 09:13:52
  • 3950

7. Reverse Integer [easy] (Python)

题目链接https://leetcode.com/problems/reverse-integer/题目原文 Reverse digits of an integer. Example1: ...
  • coder_orz
  • coder_orz
  • 2016-07-26 21:50:37
  • 3078

LeetCode 7 — Reverse Integer(C++ Java Python)

题目:http://oj.leetcode.com/problems/reverse-integer/ Reverse digits of an integer. Example1: x = 1...
  • dragon_dream
  • dragon_dream
  • 2014-02-22 10:15:19
  • 4884

LeetCode: Reverse Integer (JavaScript)

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 本地测试通过...
  • notail_woo
  • notail_woo
  • 2015-04-23 20:41:39
  • 856

【LeetCode-Algorithm】【7-Reverse Integer】【Python】

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click ...
  • IFollowRivers
  • IFollowRivers
  • 2016-09-20 19:04:47
  • 1071

LeetCode(7) Reverse Integer

本题比较简单,也比较坑爹, Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return...
  • feliciafay
  • feliciafay
  • 2013-12-04 02:02:23
  • 7908

Leetcode 7 Reverse Integer 反转数字

题目: Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return ...
  • vvaaiinn
  • vvaaiinn
  • 2015-04-20 10:28:58
  • 5024
收藏助手
不良信息举报
您举报文章:7. Reverse Integer
举报原因:
原因补充:

(最多只允许输入30个字)