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

    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.

    这道题思路非常简单,就是按照数字位反转过来就可以,基本数字操作。但是这种题的考察重点并不在于问题本身,越是简单的题目越要注意细节,一般来说整数的处理问题要注意的有两点,一点是符号,另一点是整数越界问题。代码如下: 

    用的字符串, 考虑反转后大于MAX_VALUE:

    if (Long.parseLong(s) > Integer.MAX_VALUE) {
                return 0;
            }
    防止首字母为0, 但是如果只有0的话也要考虑
    while (sb.charAt(0) == '0') {
                sb.deleteCharAt(0);
            }
     public int reverse(int x) {
            if (x == Integer.MIN_VALUE || x == 0) {
    
                return 0;
            }
            boolean isNeg = false;
            if (x < 0) {
                isNeg = !isNeg;
                x = -x;
            }
            String s = "";
            StringBuilder sb = new StringBuilder();
            s += x;
            int i = 0, j = s.length() - 1;
            while (j >= 0) {
                sb.append(s.charAt(j));           
                j--;
            }
        // 要注意!!!数字的首字母非0 while (sb.charAt(0) == '0') { sb.deleteCharAt(0); } s = sb.toString(); if (Long.parseLong(s) > Integer.MAX_VALUE) { return 0; } int ans = Integer.valueOf(s); return isNeg ? -ans : ans; }

    用%翻转, / 递进

    public int reverse(int x) {
            int res = 0;
            while (x != 0) {
                int digit = x % 10;
                x = x / 10;
                if (res > Integer.MAX_VALUE / 10|| res == Integer.MAX_VALUE && digit > 7) {
                    return 0;
                }
                if (res < Integer.MIN_VALUE / 10 || res == Integer.MIN_VALUE && digit < 8) {
                    return 0;
                    
                }
                res = res * 10 + digit;
            }
            return res;
        }
    

      

    注意Integer.MIN_VALUE的绝对值是比Integer.MAX_VALUE大1的,所以经常要单独处理。如果不先转为正数也可以,只是在后面要对符号进行一下判断。这种题目考察的就是数字的基本处理,面试的时候尽量不能错,而且对于corner case要尽量进行考虑,一般来说都是面试的第一道门槛。

  • 相关阅读:
    第八周学习总结
    《程序是怎样跑起来的》第十一章
    第七周学习总结
    《程序是怎样跑起来的》第十章
    《程序是怎样跑起的》第九章
    第五周学习总结
    《程序是怎样跑起来的》第八章
    《程序是怎样跑起来的》第七章
    抽象类与接口学习总结
    多态学习总结
  • 原文地址:https://www.cnblogs.com/apanda009/p/7307539.html
Copyright © 2011-2022 走看看