鍍金池/ 教程/ Java/ String to Integer (atoi)(轉(zhuǎn)換到整型)
ZigZag Conversion(Z型轉(zhuǎn)換)
String to Integer (atoi)(轉(zhuǎn)換到整型)
Generate Parentheses(生成括號(hào))
Longest Common Prefix(最長(zhǎng)公共前綴)
Remove Duplicates from Sorted Array(從已排序數(shù)組中移除重復(fù)元素)
Swap Nodes in Pairs(交換序列中的結(jié)點(diǎn))
Valid Parentheses(有效的括號(hào))
4 Sum(4 個(gè)數(shù)的和)
3 Sum(3 個(gè)數(shù)的和)
3 Sum Closest(最接近的 3 個(gè)數(shù)的和)
Reverse Nodes in k-Group(在K組鏈表中反轉(zhuǎn)結(jié)點(diǎn))
Regular Expression Matching (正則表達(dá)式匹配)
Two Sum
Container With Most Water(最大水容器)
Merge Two Sorted Lists(合并兩個(gè)已排序的數(shù)組)
Remove Nth Node From End of List(從列表尾部刪除第 N 個(gè)結(jié)點(diǎn))
String to Integer (atoi)(轉(zhuǎn)換到整型)
Palindrome Number(回文數(shù))
Longest Substring Without Repeating Characters
Roman to Integer(羅馬數(shù)到整型數(shù))
Integer to Roman(整型數(shù)到羅馬數(shù))
Reverse Integer(翻轉(zhuǎn)整數(shù))
Merge k Sorted Lists(合并 K 個(gè)已排序鏈表)
Implement strStr()(實(shí)現(xiàn) strStr() 函數(shù))
Longest Palindromic Substring(最大回文子字符串)
Add Two Numbers
Letter Combinations of a Phone Number(電話號(hào)碼的字母組合)

String to Integer (atoi)(轉(zhuǎn)換到整型)

翻譯

翻轉(zhuǎn)一個(gè)整型數(shù)

例 1:x = 123, 返回 321
例 2:x = -123, 返回 -321

原文

Reverse digits of an integer.

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

Have you thought about this? (來自 LeetCode 官網(wǎng))

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.

C

public class Solution
{
    public int Reverse(int x)
    {
        try
        {
            string str = Math.Abs(x).ToString();
            string newStr = (x < 0) ? "-" : "";
            for (int i = str.Length - 1; i >= 0; i--)
            {
                newStr += str[i];
            }
            return int.Parse(newStr);
        }
        catch (Exception e)
        {
            return 0;
        }
    }
}

C++(來源于網(wǎng)絡(luò))

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