国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Leet Code OJ 7. Reverse Integer

2019-11-11 06:53:57
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Reverse digits of an integer.

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

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

大意: 題目要求將一個(gè)數(shù)反轉(zhuǎn),如123反轉(zhuǎn)為321,但是有一點(diǎn)需要注意,要考慮溢出,32位的Integer范圍是:-2147483646 ~ 2147483646 1. 假如一開始就傳入大于或小于這個(gè)范圍的值,要怎么處理 2. 如果反轉(zhuǎn)后的值大于或小于這個(gè)范圍的值,要怎么處理

我的思路是: 首先把int值強(qiáng)轉(zhuǎn)為long來(lái)計(jì)算,然后在while內(nèi),從個(gè)位開始反轉(zhuǎn)

我的代碼:

public class Solution { public int reverse(int x) { int flag = 1; long nx = (long) x; if(nx < 0){ flag = -1; nx = -nx; } if(nx > Integer.MAX_VALUE){ return 0; } if(nx < 10){ return x; } long sum = 0; //反轉(zhuǎn) while(nx != 0){ sum = sum*10 + nx%10; nx /= 10; } if(sum > Integer.MAX_VALUE){ return 0; } return ((int)sum * flag); }}

Discussion的優(yōu)秀代碼: 它的高明之處是:在反轉(zhuǎn)的每一步計(jì)算過(guò)程中,判斷當(dāng)前的sum是否溢出,然后做處理; 而我的做法是,在開始和結(jié)束處處理溢出,所以代碼沒那么簡(jiǎn)潔

public class P7 { public int reverse(int x) { long rev= 0; while( x != 0){ rev= rev*10 + x % 10; x= x/10; if( rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0; } return (int) rev; }}
上一篇:牛式

下一篇:LeetCode 58. Length of Last Word

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 龙口市| 建水县| 太仆寺旗| 云浮市| 建瓯市| 太原市| 蕲春县| 中阳县| 安康市| 贺兰县| 和田县| 寿阳县| 志丹县| 沅陵县| 陆良县| 万载县| 开化县| 霸州市| 商水县| 东乡| 长乐市| 青河县| 澄迈县| 宁化县| 来凤县| 德格县| 临漳县| 南康市| 彰武县| 招远市| 土默特右旗| 雅江县| 罗山县| 邮箱| 麻阳| 泸溪县| 定西市| 瓦房店市| 连城县| 南京市| 大田县|