C++实现LeetCode(8.字符串转为整数)

[LeetCode] 8. String to Integer (atoi) 字符串转为整数

Implement atoi which converts a string to an integer.

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.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−231) is returned.

字符串转为整数是很常用的一个函数,由于输入的是字符串,所以需要考虑的情况有很多种。博主之前有一篇文章是关于验证一个字符串是否为数字的,参见 Valid Number。在那篇文章中,详细的讨论了各种情况,包括符号,自然数,小数点的出现位置,判断他们是否是数字。个人以为这道题也应该有这么多种情况。但是这题只需要考虑数字和符号的情况:

1. 若字符串开头是空格,则跳过所有空格,到第一个非空格字符,如果没有,则返回0.

2. 若第一个非空格字符是符号 +/-,则标记 sign 的真假,这道题还有个局限性,那就是在 c++ 里面,+-1 和-+1 都是认可的,都是 -1,而在此题里,则会返回0.

3. 若下一个字符不是数字,则返回0,完全不考虑小数点和自然数的情况,不过这样也好,起码省事了不少。

4. 如果下一个字符是数字,则转为整形存下来,若接下来再有非数字出现,则返回目前的结果。

5. 还需要考虑边界问题,如果超过了整型数的范围,则用边界值替代当前值。

C++ 解法:

class Solution {
public:
    int myAtoi(string str) {
        if (str.empty()) return 0;
        int sign = 1, base = 0, i = 0, 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;
    }
};

Java 解法:

public class Solution {
    public int myAtoi(String str) {
        if (str.isEmpty()) return 0;
        int sign = 1, base = 0, i = 0, n = str.length();
        while (i < n && str.charAt(i) == ' ') ++i;
        if (i < n && (str.charAt(i) == '+' || str.charAt(i) == '-')) {
            sign = (str.charAt(i++) == '+') ? 1 : -1;
        }
        while (i < n && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            base = 10 * base + (str.charAt(i++) - '0');
        }
        return base * sign;
    }
}

到此这篇关于C++实现LeetCode(8.字符串转为整数)的文章就介绍到这了,更多相关C++实现字符串转为整数内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(132.拆分回文串之二)

    [LeetCode] 132.Palindrome Partitioning II 拆分回文串之二 Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. Example: Input: "aab" Output: 1 Explan

  • C++实现LeetCode(10.正则表达式匹配)

    [LeetCode] 10. Regular Expression Matching 正则表达式匹配 Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. T

  • C++实现LeetCode(9.验证回文数字)

    [LeetCode] 9. Palindrome Number 验证回文数字 Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left

  • C++实现LeetCode(647.回文子字符串)

    [LeetCode] 647. Palindromic Substrings 回文子字符串 Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of sa

  • C++实现LeetCode(6.字型转换字符串)

    [LeetCode] 6. ZigZag Conversion 之字型转换字符串 The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P   A   H   N A P L S I I G Y  

  • C++实现LeetCode(131.拆分回文串)

    [LeetCode] 131.Palindrome Partitioning 拆分回文串 Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"

  • C++实现LeetCode(7.翻转整数)

    [LeetCode] 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 whi

  • C++实现LeetCode(验证回文字符串)

    [LeetCode] 125.Valid Palindrome 验证回文字符串 Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a

  • C++实现LeetCode(8.字符串转为整数)

    [LeetCode] 8. String to Integer (atoi) 字符串转为整数 Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this ch

  • C++实现LeetCode(43.字符串相乘)

    [LeetCode] 43. Multiply Strings 字符串相乘 Given two non-negative integers num1 and num2represented as strings, return the product of num1 and num2, also represented as a string. Example 1: Input: num1 = "2", num2 = "3" Output: "6"

  • C++ LeetCode1805字符串不同整数数目

    目录 LeetCode 1805.字符串中不同整数的数目 方法一:遍历拆分 AC代码 C++ LeetCode 1805.字符串中不同整数的数目 力扣题目链接:leetcode.cn/problems/nu… 给你一个字符串 word ,该字符串由数字和小写英文字母组成. 请你用空格替换每个不是数字的字符.例如,"a123bc34d8ef34" 将会变成 " 123  34 8  34" .注意,剩下的这些整数为(相邻彼此至少有一个空格隔开):"123&q

  • 详解Swift中对C语言接口缓存的使用以及数组与字符串转为指针类型的方法

    详解Swift中对C语言接口缓存的使用以及数组与字符串转为指针类型的方法 由于Swift编程语言属于上层编程语言,而Swift中由于为了低层的高性能计算接口,所以往往需要C语言中的指针类型,由此,在Swift编程语言刚诞生的时候就有了UnsafePointer与UnsafeMutablePointer类型,分别对应为const Type*类型与Type *类型. 而在Swift编程语言中,由于一般数组(Array)对象都无法直接用于C语言中含有指针类型的函数参数(比如:void*),所以往往需要

  • python用reduce和map把字符串转为数字的方法

    python中reduce和map简介 map(func,seq1[,seq2...]) :将函数func作用于给定序列的每个元素,并用一个列表来提供返回值:如果func为None,func表现为身份函数,返回一个含有每个序列中元素集合的n个元组的列表. reduce(func,seq[,init]) :func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:

  • JavaScript将字符串转换为整数的方法

    本文实例讲述了JavaScript将字符串转换为整数的方法.分享给大家供大家参考.具体如下: var s='1'; var s2='2'; alert(parseInt(s) parseInt(s2)); 希望本文所述对大家的javascript程序设计有所帮助.

  • java中字符串转整数及MyAtoi方法的实现

    java中字符串转整数及MyAtoi方法的实现 该题虽然和我们正常使用的字符串转整数的API中函数不一致,但是通过增加了很多额外的边界或者异常处理,可以锻炼算法思维的敏锐性和处理边界异常等问题的能力. 思路:字符串题一般考查的都是边界条件.特殊情况的处理.所以遇到此题一定要问清楚各种条件下的输入输出应该是什么样的. 这里已知的特殊情况有: 能够排除首部的空格,从第一个非空字符开始计算 允许数字以正负号(+-)开头 遇到非法字符便停止转换,返回当前已经转换的值,如果开头就是非法字符则返回0 在转换

  • js将键值对字符串转为json字符串的方法

    要转化的键值对字符 var respDesc="cardid=64157001&cardnum=1&sporder_id=PD12160428120635001&sporder_time=20160526101552": var newstr = respDesc.replace("=",":\""); var stringObj= "{" +newstr.replace("&

  • 在python中将字符串转为json对象并取值的方法

    如下所示: string =" { "status": "error", "messages": ["Could not find resource or operation 'BZK1.MapServer' on the system."], "code": 404 }" print '对象:' string print '取值:' json.loads(string)['code']

  • php中字符串和整数比较的操作方法

    今天在处理php中循环的时候,有个比比较的操作,但是结果一直不是自己预判的,于是跟踪了一下,发现了字符串和整数进行比较的时候,会把字符串转换成整数然后进行比较.这个在java,c这种强类型的语言中不会有问题,因为他们会对字符串进行转换然后比较,但是在php这种弱类型中,可以直接比较的时候,就会有问题. $a = "梦回故里"; if($a==0){ echo "等于"; }else{ echo "不等于"; } 比如下面这段代码,一开始以为会输出

随机推荐