• 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
  • 相关阅读:
    iOS9 HTTP 不能正常使用的解决办法
    IOS UIWebView的一些用法总结
    顺序查找
    循环队列
    队列的链式存储实现
    栈的链式存储实现
    顺序表的实现
    MessageBox函数
    二分法查找
    冒泡排序
  • 原文地址:https://www.cnblogs.com/varcom/p/4554788.html
Copyright © 2020-2023  润新知