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

    二、

    解题思路:

    在取每个位置上的数字同时将之前所求得数字的和上升一位,具体来说在取出个位上的数字同时,准备将他放到最高位。

    即:边取数,边构造新数。

    源代码如下:


    //遇到溢出问题。
    class Solution {
    public:
    int reverse(int x) {
    int res=0;
    while(x!=0)
    {
    if(abs(res)>INT_MAX/10)//在溢出之前进行判断,防止溢出。
    {
    return 0;
    }
    res=res*10+x%10;
    x/=10;
    }
    return res;
    }

    };

    三、

    总结:

    1:注意防止溢出的方法,在每次取数构成新数的同时,通过查看旧数的取值范围来确定是否越界。

    2:一趟循环完成所有任务的思路,需要养成。

  • 相关阅读:
    .hpp文件
    最小高度的BST
    检查图中的有向路径
    c++ 对象内存布局详解
    链表求差
    offer--链表反转和从尾到头打印链表
    平衡二叉树的判断
    java 抽象类和接口
    原型模式--prototype
    装饰模式decorator
  • 原文地址:https://www.cnblogs.com/zydxx/p/9959805.html
Copyright © 2011-2022 走看看