LeetCode:Reverse Integer

简介:

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter)


leetcode的测试样例中似乎没有翻转后溢出的情况。                      本文地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class  Solution {
public :
     int  reverse( int  x) {
         bool  isPositive = true ;
         if (x < 0){isPositive = false ; x *= -1;}
         long  long  res = 0; //为了防止溢出,用long long
         while (x)
         {
             res = res*10 + x%10;
             x /= 10;
         }
         if (res > INT_MAX) return  isPositive ? INT_MAX : INT_MIN;
         if (!isPositive) return  res*-1;
         else  return  res;
     }
};





本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3735866.html,如需转载请自行联系原作者

目录
相关文章
|
机器学习/深度学习 NoSQL 算法
LeetCode 344. 反转字符串 Reverse String
LeetCode 344. 反转字符串 Reverse String
LeetCode 206. 反转链表 Reverse Linked List
LeetCode 206. 反转链表 Reverse Linked List
|
机器学习/深度学习
LeetCode 397. Integer Replacement
给定一个正整数 n,你可以做如下操作: 1. 如果 n 是偶数,则用 n / 2替换 n。 2. 如果 n 是奇数,则可以用 n + 1或n - 1替换 n。 n 变为 1 所需的最小替换次数是多少?
55 0
|
索引
LeetCode 345. Reverse Vowels of a String
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
54 0
LeetCode 345. Reverse Vowels of a String
|
机器学习/深度学习 NoSQL
LeetCode 344. Reverse String
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
71 0
LeetCode 344. Reverse String
LeetCode 343. Integer Break
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
49 0
LeetCode 343. Integer Break
LeetCode 190. Reverse Bits
颠倒给定的 32 位无符号整数的二进制位。
65 0
LeetCode 190. Reverse Bits
LeetCode 150. Evaluate Reverse Polish Notation
根据逆波兰表示法,求表达式的值。 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
28 0
LeetCode 150. Evaluate Reverse Polish Notation
LeetCode 92. Reverse Linked List II
给定一个链表,反转指定的子序列.
59 0
LeetCode 92. Reverse Linked List II
LeetCode之Reverse String II
LeetCode之Reverse String II
85 0