leetcode----------Reverse Integer

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   sp   for   

題目 Reverse Integer
通過率 34.2%
難度 Easy

Reverse digits of an integer.

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

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

    這是一個數字反轉的問題,翻轉的思想是將原數不斷模10取餘再除10,從個位按照移位不斷得到各個位置的數字,正好是結果從高位到低位的各個位置的數字,對結果的處理正好和原數相反,不斷乘10加餘數。

   此題目需要注意的幾點是:

   1. 首先對原數x按照幾個範圍進行劃分,a.-10<x<10的範圍直接返回x; b.其他情況;

   2. 需要設定一個boolean類型變數來標記原數的符號,負數需要轉換為正數進行處理,結果再附加上符號;

   3. 注意越界的情況,原數不會出現越界,但是反轉以後的數字會存在越界的情況!!!!

java代碼:

public class Solution {    public int reverse(int x) {        if(x>-10&&x<10) return x;        boolean flag = x>0?true:false;        long temp = x;        long result =0;        temp = temp>0?temp:-temp;        while(temp>0)        {            result = result*10+temp%10;            temp /=10;        }        if(result>Integer.MAX_VALUE){            return 0;        }else if(flag)        {            return (int)result;        }else        {            return -(int)result;        }    }}

 

leetcode----------Reverse Integer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.