leetcode 7 Reverse Integer

简介: Reverse digits of an integer.Example1: x = 123, return 321 Example2: x = -123, return -321 click to show spoilers.

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.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

非常优雅的解决方案:

这里写图片描述

class Solution {
public:
  int reverse(int x) 
{
    static const int overflow = INT_MAX/10;
    const int mod = x>0 ? 10 : -10;
    int r = 0;


    while(x)
    {
        if(r > overflow || r < -overflow)
            return 0;

        r = (x % mod) + r * 10;
        x = x / 10;
    }

    return r;


}

};
相关文章
|
机器学习/深度学习 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 所需的最小替换次数是多少?
53 0
|
机器学习/深度学习 NoSQL
LeetCode 344. Reverse String
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
70 0
LeetCode 344. Reverse String
LeetCode 343. Integer Break
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
48 0
LeetCode 343. Integer Break
LeetCode 190. Reverse Bits
颠倒给定的 32 位无符号整数的二进制位。
63 0
LeetCode 190. Reverse Bits
LeetCode之Reverse String II
LeetCode之Reverse String II
84 0
LeetCode之Reverse String
LeetCode之Reverse String
71 0
LeetCode之Reverse Integer
LeetCode之Reverse Integer
77 0
LeetCode 150:逆波兰表达式求值 Evaluate Reverse Polish Notation
题目: 根据逆波兰表示法,求表达式的值。 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. 说明: 整数除法只保留整数部分。
1354 0

热门文章

最新文章