LeetCode开心刷题第四天——7逆序8字符转数字

7 Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Special Point:

PS:真正好的代码,果真是简洁又明晰的

1.对于溢出的考察

本身不溢出的数,经过逆序后可能溢出,所以要进行判断

2.对于逆序的考察

逆序的处理十分干净利落

res保存逆序后的数,初始值为0,每次都需要乘10再加新的值。每次比较是否比INT_MAX最大值除10的值大,这样如果大了,再乘10一定也会大,所以直接报溢出0

res=res*10+x%10

x/=10

可以以后作为小模块用。

其实如果数目过大,就需要用字符串表示或者变换,但是这个题目自己限定了溢出直接用0代替,这就是这道题的简单之处

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

在贴出答案的同时,OJ 还提了一个问题 To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why? (214748364 即为 INT_MAX / 10)

为什么不用 check 是否等于 214748364 呢,因为输入的x也是一个整型数,所以x的范围也应该在 -2147483648~2147483647 之间,那么x的第一位只能是1或者2,翻转之后 res 的最后一位只能是1或2,所以 res 只能是 2147483641 或 2147483642 都在 int 的范围内。但是它们对应的x为 1463847412 和 2463847412,后者超出了数值范围。所以当过程中 res 等于 214748364 时, 输入的x只能为 1463847412, 翻转后的结果为 2147483641,都在正确的范围内,所以不用 check。

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

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.

题目翻译:

实现atoi,将字符串转换为整数。
提示:仔细考虑所有可能的输入情况。如果你想要挑战,请不要看下面,并问自己有哪些可能的输入情况。

注:这个问题有意模糊说明(即没有给定输入说明)。你负责预先收集所有的输入需求。

atoi的需求:
该函数首先丢弃尽可能多的空白(whitespace )字符直到遇到一个非空白字符。从这个字符开始,有一个可选的初始加号或减号,后面是尽可能多的数字,把它们当成数值解释。

该字符串在形成整数的字符后面可以包含额外字符,它们会被忽略,对这个函数的行为没有影响。

如果str中的第一个非空白字符序列不是一个有效的整数,或者如果这样的序列不存在(str是空的或只包含空白字符),不执行任何转换。

如果没有执行任何有效的转换,则返回0。如果正确的值超出了可表示的值的范围,返回INT_MAX(2147483647)或INT_MIN(-2147483648)。

分析:
        注意考虑特殊情况。

Special Point:

这是个medium的题,其实每个题都有hard的潜质,只是题目好心限制了一些条件,比如这个

只用管第一个是不是正负号,后面的数字照单全收,而不是则可以一竿子打死,这是十分便利的

比起上面特殊点就在于,这是个字符串,所以可能处理溢出和之前不一样。上面由于输入的是int所以判断不需要有等号的情况,但这个不同

class Solution {
public:
    int myAtoi(string str) {
        if(str.empty()) return 0;
        int base=0,i=0,sign=1,n=str.size();
        while(i<n&&str[i]==‘ ‘) i++;
        if(i<n&&(str[i]==‘+‘||str[i]==‘-‘))
            //注意这是在顺序处理字符串,所以每判断完一个要++
            sign=(str[i++]==‘+‘)?1:-1;
        while(i<n&&str[i]>=‘0‘&&str[i]<=‘9‘)
        {
            if(base>INT_MAX/10||(base==INT_MAX/10&&str[i]-‘0‘>7))
                return (sign==1)?INT_MAX:INT_MIN;

            base=10*base+(str[i++]-‘0‘);
        }
        return base*sign;
    }
};

原文地址:https://www.cnblogs.com/Marigolci/p/11007360.html

时间: 2024-10-07 15:17:54

LeetCode开心刷题第四天——7逆序8字符转数字的相关文章

LeetCode开心刷题十四天——25Reverse Nodes in k-Group

25. Reverse Nodes in k-Group Hard 1222257FavoriteShare Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number

LeetCode开心刷题五十一天——118. Pascal&#39;s Triangle 接触跳转表概念,不知用处 lamda逗号导致表达式加法奇怪不理解119. Pascal&#39;s Triangle II

118. Pascal's Triangle Easy 87984FavoriteShare Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 5 Output: [ [1],

LeetCode开心刷题十三天——24

习惯就是人生的最大指导 ——休谟 24. Swap Nodes in Pairs Medium 1209107FavoriteShare Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed. 防止用增加值,存储前后变量只进行值交换,而不处理

LeetCode开心刷题五十六天——128. Longest Consecutive Sequence

最近刷题进展尚可,但是形式变化了下,因为感觉眼睛会看瞎,所以好多写在纸上.本来想放到文件夹存储起来,但是太容易丢了,明天整理下,赶紧拍上来把 今晚是周末,这一周都在不停的学学学,我想下周怕是不能睡午觉了,中午回去床对我的诱惑太大了,我得想办法,一进门先把被褥收起来,再放个欢快的歌,中午少吃点,加油小可爱 之前欠下的烂帐,把太多简单题做完,导致剩下的都是难题,所以万万记住一点捷径都不要走 128看花花酱大神的解法,发现对hashtable的了解十分不足,甚至一些常见函数都不知道是干什么的 这道题涉

LeetCode开心刷题四十二天——56. Merge Intervals

56. Merge Intervals Medium 2509194FavoriteShare Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, mer

LeetCode开心刷题四十八天——71. Simplify Path

71. Simplify Path Medium 5101348FavoriteShare Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. In a UNIX-style file system, a period . refers to the current directory. Furthermore, a do

LeetCode开心刷题五十五天——117. Populating Next Right Pointers in Each Node II

问题亟待解决: 1.一个问题一直困扰着我,想看下别人是怎么处理树的输入的,最好是以层级遍历这种清楚直观的方式. 2.关于指针*的使用 因此也导致代码不完整,没有主函数对Solution类的调用 117. Populating Next Right Pointers in Each Node II Medium 1161165FavoriteShare Given a binary tree struct Node { int val; Node *left; Node *right; Node

LeetCode开心刷题第九天——17Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number Medium 2241301FavoriteShare Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the teleph

LeetCode开心刷题十六天——29. Divide Two Integers*

From now on,I grade the questions I've done,* less means more difficult *** done by myself **need see answer,but I can reappear it *need see answer&hard to reappear 29. Divide Two Integers Medium 7003349FavoriteShare Given two integers dividend and d