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

    解答:将需要翻转的整数先求余,假设结果为0,result = result * 10 + x % 10;假如x / 10 != 0,则继续将余数按照前面的方式添加到result中

    注意:整数最大取值为:2147483647,最小的取值为:-2147483648,处理result时候,需要注意先将result与最大整数,最小整数求余的值进行比较。

    java代码:

    public class ReverseInteger {
        public static int reverse(int x) {
            int result = 0;
            do{
                if(result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && x % 10 > 7)) return 0;
                if(result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && x % 10 < -8)) return 0;
                result = result * 10 + x % 10;
            }while((x = x / 10) != 0);
            return result;
        }
    
        public static void main(String[] args){
            int result = reverse(1534236469);
            System.out.println(result);
            System.out.println(Integer.MAX_VALUE);
            System.out.println(Integer.MIN_VALUE);
            System.out.println(-14 / 10);
            System.out.println(-14 % 10);
        }
    }

    result:

    0
    2147483647
    -2147483648
    -1
    -4

  • 相关阅读:
    托管C++中System::String^ 转换为 char*
    Oracle-11:联合查询
    Oracle-10:分析函数
    Oracle-09:聚合函数
    Oracle-08:连接查询
    Oracle-07:别名,去重,子查询
    Oracle-06:DML语言数据表的操作
    Oracle-05:伪表dual
    Oracle-04:DDL语言数据表的操作
    Oracle-03:关系型数据库和非关系的数据库的各自优缺点与区别
  • 原文地址:https://www.cnblogs.com/feng-ying/p/10504860.html
Copyright © 2011-2022 走看看