zoukankan      html  css  js  c++  java
  • 7. Reverse 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 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.

    (1)思想1:设立一个falg=1,判断x<0,则令flag=-1;然后仍然是将数字转换成字符串,进行str[i] 与 str[len-1-i] 的一个互换,互换完成之后再将字符串转化成数字,此时需要注意的是:数字的范围是-2^32 ~ 2^32-1,所以必须对转换前和转换后的数字均进行判断,在这个范围内,则返回 flag*转换后的数字,否则返回0。

    C++:

     1 class Solution {
     2 public:
     3     int reverse(int x) {
     4         int flag=1;
     5         if(x<0)
     6             flag=-1;
     7         string str=to_string(abs(x));
     8         int len=str.size();
     9         for(int i=0;i<len/2;i++)
    10         {
    11             char c=str[i];
    12             str[i]=str[len-1-i];
    13             str[len-1-i]=c;
    14         }
    15         long int result = flag*atol(str.c_str());
    16         if(x>pow(2,31)-1 || x<-1*pow(2,31) || result>pow(2,31)-1 || result<-1*pow(2,31))
    17             return 0;
    18         return result;
    19     }
    20 };
  • 相关阅读:
    近期计划安排
    线段树+离散化+染色
    矩阵快速幂(共轭函数两种递推式)
    树状数组求区间最值和单点更新
    矩阵快速幂(共轭函数)
    树状数组之区间更新与查询
    Python List min()方法
    Python List max()方法
    Python List len()方法
    Python List cmp()方法
  • 原文地址:https://www.cnblogs.com/sword-/p/8041654.html
Copyright © 2011-2022 走看看