摘要:原題目為難度此題讓我們輸出給定一個整數(shù)的倒序數(shù)比如倒序為倒序為但是如果倒序的過程中發(fā)生整型溢出我們就輸出倒序不復雜關(guān)鍵在于如何判定將要溢出最終的程序如下其中是獲取的個位數(shù)字判定下一步是否將要溢出使用
原題目為:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321Have 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.
難度: Easy
此題讓我們輸出給定一個整數(shù)的倒序數(shù), 比如123倒序為321, -123倒序為-321. 但是如果倒序的過程中發(fā)生整型溢出, 我們就輸出0.
倒序不復雜, 關(guān)鍵在于如何判定將要溢出.
最終AC的程序如下:
public class Solution { public int reverse(int x) { int x1 = Math.abs(x); int rev = 0; while (x1 > 0) { if (rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10) { return 0; } rev = rev * 10 + (x1 - (x1 / 10) * 10); x1 = x1 / 10; } if (x > 0) { return rev; } else { return -rev; } } }
其中 x1 - (x1 / 10) * 10 是獲取x1的個位數(shù)字, 判定下一步是否將要溢出, 使用 rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10 .
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.hztianpu.com/yun/66514.html
摘要:字符串法復雜度時間空間思路先將數(shù)字轉(zhuǎn)化為字符串,然后將字符串倒序輸出,并轉(zhuǎn)回數(shù)字。模十法復雜度時間空間思路通過對數(shù)字模十取余得到它的最低位。除了檢查溢出返回特定值以外,有沒有別的方法處理溢出可以使用代碼塊排除異常。 Reverse Integer Reverse digits of an integer.Example1: x = 123, return 321Example2: x ...
摘要:題目詳情題目要求我們給出一個數(shù)的翻轉(zhuǎn)數(shù)想法這道題主要的坑就是在于一個數(shù)值的輸入,在進行翻轉(zhuǎn)操作之后,不一定還符合的范圍,可能會造成異常。我們可以通過每次獲得整數(shù)除的余數(shù),來確定當前整數(shù)的最后一位。 題目詳情 Given a 32-bit signed integer, reverse digits of an integer.題目要求我們給出一個數(shù)的翻轉(zhuǎn)數(shù) Example 1:Inpu...
摘要:第一時間想到這是經(jīng)典的取模取余運算,但是寫的過程中遇到了很多問題這么簡單一題基礎做法取一個整數(shù)的最后一位數(shù)字只要把這個整數(shù)就可以,要取除最后一位數(shù)字之外的其它數(shù)字只要是沒有長度函數(shù)的,需要轉(zhuǎn)化成才能使用長度函數(shù)用這個方法最大的難點在 Easy 007 Reverse Integer Description: Given a 32-bit signed integer, reverse ...
摘要:判斷溢出這里使用了中的類整數(shù)類,縮寫就是的靜態(tài)變量和,就能直接得到整型變量可表示數(shù)值的上下限。當結(jié)果不在此范圍內(nèi)時,則溢出,并返回否則返回正常結(jié)果。 要點 這一題的要點有三個: 接收長度不同的數(shù)字并翻轉(zhuǎn) 判斷結(jié)果是否溢出 解決方法 翻轉(zhuǎn):為了能夠接收不同長度的數(shù)字進行反轉(zhuǎn)操作,我們使用循環(huán)結(jié)構(gòu)進行操作。(注:這里創(chuàng)建的sum變量一定要用long類型而不能用int,原因是采用int...
摘要:詳細介紹將其他值轉(zhuǎn)成數(shù)字值。此方法更改數(shù)組的長度。詳細介紹解題思路首先,將傳入的數(shù)字轉(zhuǎn)換成字符串,并分割成數(shù)組。本許可協(xié)議授權(quán)之外的使用權(quán)限可以從處獲得。 Create by jsliang on 2019-05-19 09:42:39 Recently revised in 2019-05-19 16:08:24 Hello 小伙伴們,如果覺得本文還不錯,記得給個 star , 小伙伴們...
閱讀 2558·2023-04-26 02:54
閱讀 2507·2021-10-14 09:43
閱讀 3703·2021-09-22 15:19
閱讀 2993·2019-08-30 15:44
閱讀 2844·2019-08-30 12:54
閱讀 1121·2019-08-29 18:43
閱讀 2073·2019-08-29 17:12
閱讀 1469·2019-08-29 16:40