【Reverse Integer】cpp

题目:

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) {
            int v = x;
            queue<int> que;
            while ( true )
            {
                int digit = v % 10;
                que.push(digit);
                v = v / 10;
                if ( abs(v)<10 ) break;
            }
            if ( v!=0) que.push(v);
            int ret = 0;
            while ( !que.empty() )
            {
                // cout << que.front() << endl;
                if ( ret > INT_MAX/10 || ret < INT_MIN/10) return 0; // overflow
                ret = ret * 10 + que.front();
                que.pop();
            }
            return ret;
    }
};

tips:

主要考虑出现overflow怎么处理,上述代码第一次写用了queue的结构,先进先出,方便调试各种case。

AC后对上述的代码进行了改进,改进结果如下,也可以AC。

class Solution {
public:
    int reverse(int x) {
            int ret = 0;
            while (x)
            {
                if ( ret > INT_MAX/10 || ret < INT_MIN/10 ) return 0;
                ret = ret*10 + x%10;
                x = x /10;
            }
            return ret;
    }
};

可以看到代码精炼了很多。另外判断是否越界不要直接比较 value>INT_MAX或者value<INT_MIN一般都是比较最大值除以10;因为value本身就越界了,再跟最大值比较也没有意义了。这是一个放缩的技巧。

时间: 2024-10-29 04:10:48

【Reverse Integer】cpp的相关文章

【Palindrome Number】cpp

题目: Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using

【Roman To Integer】cpp

题目: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 代码: class Solution { public: int romanToInt(string s) { const int size = 7; std::map<char, int> symbol_value; char symbol_ori[size] = {'M

【Gray Code】cpp

题目: The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0

【Reorder List】cpp

题目: Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example,Given {1,2,3,4}, reorder it to {1,4,2,3}. 代码: /** * Definition for singly-linked list.

【Next Permutation】cpp

题目: Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The repla

【Word Break】cpp

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true becau

【Sudoku Solver】cpp

题目: Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 代码: cla

【Subsets II】cpp

题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,2], a sol

【LRU Cache】cpp

题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.