Leetcode 题目整理-2 Reverse Integer && String to Integer

今天的两道题关于基本数据类型的探讨,估计也是要考虑各种情况,要细致学习

7. 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?

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.

注:颠倒整数中的每一位,符号位保留。估计会有一些极端情况需要考虑,这里指出了几个,如,末位为0 翻转之后是什么?又如,如果翻转之后超出了数据类型的表达范围怎么办?。。。可能还会遇到其它的困难^~^

解:在考虑最值的时候必须另外定义最值为int 常量,否则的话系统会给他分配一个合适的类型

直接写成这个做判断是不可以的。

if (temp >0x7fffffff || temp < 0x80000000)
        {
            return result;
        }

下面是提交通过的代码:

class Solution {
public:
    int reverse(int x) {
            int result{0};
            long long temp{0};
            const int max_int=0x7fffffff;// 0111 1111 1111 1111 ... 1111 32bit
            const int min_int=0x80000000;//1000 0000 0000 0000 ... 0000 32bit

    while (x != 0)
    {
        temp = temp*10 + x%10;
        x = x / 10;
        if (temp > max_int || temp < min_int)
        {
            return result;
        }
    }
    result = temp;
    return result;
    }
};

8. String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

注:把一个字符串转换为整数。要考虑所有可能的输入情况。这个问题在《c++入门经典》中设计计算器时遇到过,只是当时没有细细的分析每一种情况,现在要好好看看。

解:这个简直是不可理喻,一下列举了一些可能出现的情况

input:“+ - 2”expected:0

input:“+ 01   1 2”expected:1

input:“+ + 2”expected:0

input:“-012a34”expected:12

input:"    +11191657170"expected:2147483647

代码如下,有待精简:

long long  result{ 0 };
    int n{ 0 };//位数
    int sign{ 1 }, p_n_flag{ 0 }, zero_flag{0};
    for (string::iterator s_i = str.begin(); s_i != str.end(); s_i++)
    {
        if (*s_i == ‘-‘)
        {
            if (p_n_flag==0)
            {
                p_n_flag = 1;
                sign = -1;
                continue;
            }
            else
            {
                sign = 0;//如果出现两次被认为是非法输入
                break;
            }
        }
        if (*s_i == ‘+‘)
        {
            if (p_n_flag == 0)
            {
                p_n_flag = 1;
                sign = 1;
                continue;
            }
            else
            {
                sign = 0;
                break;
            }
        }
        if (*s_i == ‘ ‘)
        {
            if (n == 0 && zero_flag == 0 && p_n_flag==0)
            { continue; }
            else
            {break;}
        }
        if (*s_i == ‘0‘)
        {
            zero_flag = 1;
            if (n == 0)
            {continue;}
            else
            {
                n = n + 1;
                result = result * 10;
                if (result > INT_MAX)
                {

                    switch (sign)
                    {
                    case 0:return 0;
                    case 1:return INT_MAX;
                    case -1:return INT_MIN;
                    default:
                        break;
                    }
                }
                else
                {continue;}

            }
        }
        if ((*s_i) > ‘0‘ && ((*s_i) < ‘9‘ || (*s_i) == ‘9‘))
        {
            n = n + 1;
            //result = result * 10 + ((*s_i) - 48);
            result = result * 10 + ((*s_i) - ‘0‘);//最后一个括号里不用显式的值48 而是用‘0’
            cout << result << endl;
            if (result > INT_MAX)
            {

                switch (sign)
                {
                case 0:return 0;
                case 1:return INT_MAX;
                case -1:return INT_MIN;
                default:
                    break;
                }
            }
        }
        else
        {
            break;
        }

    }
    result = result*sign;

    return result;
时间: 2024-10-10 19:50:02

Leetcode 题目整理-2 Reverse Integer && String to Integer的相关文章

Leetcode 题目整理-3 Palindrome Number &amp; Roman to Integer

9. Palindrome Number 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 res

LeetCode7~9 Reverse Integer/String to Integer (atoi)/Palindrome Number

一:Reverse Integer 题目: Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 链接:https://leetcode.com/problems/reverse-integer/ 分析:这题通过不断取余将余数存放在一个vector中,然后乘以相应的10^i次方相加即可,这里主要考虑是否overflow,因此将result设为long long int

Leetcode 题目整理-2

今天的两道题关于基本数据类型的探讨,估计也是要考虑各种情况,要细致学习 7. Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if

Leetcode 题目整理-3

9. Palindrome Number 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 res

Leetcode 题目整理-4

14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings. 注:这题竟然连个示例都没有,说明特殊情况并不多,就是要找出所有字符串的最长公共前缀.他应该不会超过所有字符串中最短的那个,可以试着找出最短长度n,然后每个都读取和比较n个,并根据情况不断减小那个n. 19. Remove Nth Node From End of List

Leetcode 题目整理 Sqrt &amp;&amp; Search Insert Position

Sqrt(x) Implement int sqrt(int x). Compute and return the square root of x. 注:这里的输入输出都是整数说明不会出现 sqrt(7)这种情况,思路一就是应用二分法进行查找.每次给出中间值,然后比对cur的平方与目标值的大小.需要先设定两个变量用来存放左右游标. 这里要考虑一下整型溢出的问题,另外,即使不能开出整数的也要近似给出整数部分,不能忽略. 代码如下: int Solution::mySqrt(int x) { //

【LeetCode 8_字符串_实现】String to Integer (atoi)

1 enum status{VALID = 0, INVALID}; 2 int g_status; 3 4 long long SubStrToInt(const char* str, bool minus) 5 { 6 long long num = 0; 7 int flag = minus ? -1 : 1; 8 9 while (*str != '\0') { 10 if (*str >= '0' && *str <= '9') { 11 num = num * 10

LeetCode题目1 - Reverse Integer

Reverse digits of an integer.Example1: x = 123, return 321Example2: x = -123, return -321Discuss: 1.If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.   2.Reversed integer overflow. public static int ReverseIntege

[leetcode] [leetcode] String to Integer (atoi)

Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be spe