zoukankan      html  css  js  c++  java
  • 3.Reverse Integer

    Description:

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    click to show spoilers.

    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

    难度:easy

    题目要求把给定一个int整数逆置,当发生溢出情况时返回0

    把整数逆置的思路如下:

    1.对目标整数x用%10求余,得到它的最低位数字a

    2.数字a扩充10倍,同时x减少10倍

    3.用temp暂存第2步两者的和

    当x不为0时不断重复上述过程,这样就能得到目标整数x的逆置,此时代码如下

    class Solution {
    public:
      int reverse(int x) {
        int answer = 0;
        while(x){
          int temp = answer*10 + x%10;
          answer = temp;
          x /= 10;
            }
        return answer;
      }
    };

         但这里的代码并不完整,因为没有考虑题目要求的溢出情况

          题目所给的目标整数x字节大小为32位,要检测它是否溢出应该把answer的字节数设置得比x大,因此上面代码的answer应用long long定义(之所以不用long,是因为在32位编译器中用long定义的字节大小与int一样),然后在最后加上一个溢出检测条件,最终代码如下

    class Solution {
    public:
      int reverse(int x) {
        long long answer = 0;
        while(x){
          int temp = answer*10 + x%10;
          answer = temp;
          x /= 10;
          }
        return (answer > INT_MAX || answer < INT_MIN)? 0: answer;
      }
    };

  • 相关阅读:
    LeetCode Path Sum II
    LeetCode Longest Palindromic Substring
    LeetCode Populating Next Right Pointers in Each Node II
    LeetCode Best Time to Buy and Sell Stock III
    LeetCode Binary Tree Maximum Path Sum
    LeetCode Find Peak Element
    LeetCode Maximum Product Subarray
    LeetCode Intersection of Two Linked Lists
    一天一个设计模式(1)——工厂模式
    PHP迭代器 Iterator
  • 原文地址:https://www.cnblogs.com/sarahp/p/6580783.html
Copyright © 2011-2022 走看看