zoukankan      html  css  js  c++  java
  • Reverse Integer

     1 typedef long long  lld;
     2 lld mn=-((lld)1<<32-1);
     3 lld mx=(lld)1<<32-1;
     4 class Solution {
     5 public:
     6     int reverse(int x) {
     7         lld ans=0;
     8         int sign=0;
     9         if(x<0)
    10         {
    11             sign=1;
    12             x=-x;
    13         }
    14         while(x)
    15         {
    16             ans=ans*10+x%10;
    17             x/=10;
    18         }
    19         if(sign)
    20             ans=-ans;
    21         if(ans>mx||ans<mn)
    22             ans=0;
    23         return (int)ans;
    24     }
    25 };
    View Code

    1、求int的最大最小值可以用位运算,用long int 保存

    2、用取余法得到reverse的数,就可以不用考虑前导零,只需要考虑负数和溢出情况

    3、根据负数取余仍旧是负数,-8%10=-8  ,-52%10=-2

      所以也可以不考虑负数情况

     1 typedef long long   lld;
     2 lld mn=-(lld)1<<32;
     3 lld mx=(lld)1<<32-1;
     4 class Solution {
     5 public:
     6     int reverse(int x) {
     7         lld ans=0;
     8         while(x)
     9         {
    10             ans=ans*10+x%10;
    11             x/=10;
    12         }
    13         if(ans>mx||ans<mn)
    14             ans=0;
    15         return (int)ans;
    16     }
    17 };
    View Code
  • 相关阅读:
    Cocos2d-x之Vector<T>
    Cocos2d-x之Array
    Cocos2d-x之Value
    Cocos2d-x之String
    Cocos2d-x中使用的数据容器类
    Cocos2d-x之Action
    Cocos2d-x之定时器
    Cocos2d-x之MessageBox
    Cocos2d-x之Log输出机制
    Cocos2d-x之事件处理机制
  • 原文地址:https://www.cnblogs.com/varcom/p/4554788.html
Copyright © 2011-2022 走看看