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

    题目: 

      Reverse digits of an integer.

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

    思路:不断取最低位加到先前值得后面,如下:

            while(x!=0){
              res=res*10+x%10;
              x/=10;
            }

       还要注意反转后可能会出现溢出的情况。

    public class Solution {
        public int reverse(int x) {
            long res=0;
            while(x!=0){
                res=res*10+x%10;
                x/=10;
            }
            
            if(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE){
                return 0;
            }else{
                return (int)res;
            }
        }
    }
    

      

  • 相关阅读:
    history对象
    排序算法总结
    Boltzmann机
    Sort Colors
    First Missing Positive
    Sort List
    Insertion Sort List
    Merge Two Sorted Lists
    Merge Sorted Array
    Sum Root to Leaf Numbers
  • 原文地址:https://www.cnblogs.com/zhstudy/p/5999369.html
Copyright © 2011-2022 走看看