zoukankan      html  css  js  c++  java
  • 7. Reverse Integer 反转整数

    [抄题]:

    将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

    样例

    给定 x = 123,返回 321

    给定 x = -123,返回 -321

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    负数、末尾有0均可用该方法处理

    [思维问题]:

    [一句话思路]:

    离一位数、一边变长 另一边变短

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. 不知道newres怎么变大:依靠res来递推变大

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    1. 不知道newres怎么变大:依靠res来递推变大

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    public class Solution {
        /**
         * @param n: the integer to be reversed
         * @return: the reversed integer
         */
        public int reverse(int x) {
            //ini
            int res = 0, newRes = 0;
            
            while (x != 0) {
                int tail = x % 10;
                newRes = res * 10 + tail;
                if ((newRes - tail) / 10 != res) {
                    return 0;
                }
                res = newRes;
                x = x / 10;
            }
            
            //return 
            return newRes;
        }
    }
    View Code
  • 相关阅读:
    腾讯为什么会出Q立方浏览器?
    String,StringBuffer与StringBuilder的区别??
    Linux Socket编程(不限Linux)
    将div显示在屏幕正中央
    计算鼠标坐标是否在指定范围内
    正则
    ajax异步通信
    CSS Float 换行
    jQuery强大的jQuery选择器
    给display字段增加筛选功能
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8975894.html
Copyright © 2011-2022 走看看