码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]7. Reverse Integer反转整数

时间:2019-04-04 09:16:47      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:str   bre   style   etc   log   eve   handle   sed   public   

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

题意:

给定一个10进制整数,翻转它。

 

Solution1: directly do the simulation

Two tricky parts to be handled:

(1) overflow :  32-bit signed integer range: [−231,  231 − 1],  whihc means [−2,147,483,648  2,147,483,647].  What if input is 2,147,483,647, after reversing, it will be 7,463,847,412.

(2) negative numbers

 

code:

 1 /*
 2   Time Complexity:  O(log(n))  coz we just travese half part of original input
 3   Space Complexity: O(1) 
 4 */
 5 class Solution {
 6     public int reverse(int input) {
 7         long sum = 0; 
 8         while(input !=0){
 9             sum = sum*10 + input %10;
10             input = input /10;
11             
12             if(sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE){
13                 sum = 0;  // returns 0 when the reversed integer overflows
14                 break;
15             }
16         }  
17         return (int)sum;
18     }
19 }

 

[leetcode]7. Reverse Integer反转整数

标签:str   bre   style   etc   log   eve   handle   sed   public   

原文地址:https://www.cnblogs.com/liuliu5151/p/10652711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!