`
SunnyYoona
  • 浏览: 366913 次
社区版块
存档分类
最新评论

LeetCode之 String to Integer (atoi)

 
阅读更多

【题目】

点击打开链接

Implementatoito 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函数功能,将字符串转换为整数。

【分析】

细节题:

要仔细考虑不同的测试用例:

1. -3445 -> -345

2. -34hhf67 -> -34

3. +56 -> 56

4. ++1 -> 0

5. ++a -> 0

6. 溢出数据:-2147483649 ->-2147483648

2147483649->-2147483647

【代码】

/*********************************
*   日期:2014-02-05
*   作者:SJF0115
*   题号: String to Integer (atoi)
*   来源:http://oj.leetcode.com/problems/string-to-integer-atoi/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <limits.h>
using namespace std;


class Solution {
public:
    int atoi(const char *str) {
        if(str == NULL){
            return 0;
        }
        int n = strlen(str);
        long long result = 0;
        int flag = 1;
        int index = 0;
        //过滤空格
        while(str[index] == ' '){
            index++;
        }
        //判断是否有正负号
        if(str[index] == '-'){
            flag = -1;
            index++;
        }
        else if(str[index] == '+'){
            flag = 1;
            index++;
        }
        for(int i = index;i < n;i++){
            if(str[i] < '0' || str[i] > '9'){
                break;
            }
            result = result * 10 + (str[i] - '0');
            if(flag == 1 && result > INT_MAX){
                return INT_MAX;
            }
            else if(flag == -1 && -1*result < INT_MIN){
                return INT_MIN;
            }
        }
        return (int)flag * result;
    }
};

int main() {
    Solution solution;
    char *str = "2147483649";
    int result = solution.atoi(str);
    cout<<result<<endl;
    return 0;
}

【代码2】

class Solution {
public:
    int atoi(const char *str) {
        if(str == NULL){
            return 0;
        }
        int n = strlen(str);
        int result = 0;
        int flag = 1;
        int index = 0;
        //过滤空格
        while(str[index] == ' '){
            index++;
        }
        //判断是否有正负号
        if(str[index] == '-'){
            flag = -1;
            index++;
        }
        else if(str[index] == '+'){
            flag = 1;
            index++;
        }
        for(int i = index;i < n;i++){
            if(str[i] < '0' || str[i] > '9'){
                break;
            }
            //判断是否溢出
            if(result > INT_MAX / 10 || (result == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10)){
                return flag == -1?INT_MIN:INT_MAX;
            }
            result = result * 10 + (str[i] - '0');
        }
        return flag * result;
    }
};


分享到:
评论

相关推荐

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

    leetcode-String-to-Integer-atoi

    leetcode字符串转换为整数

    leetcode中文版-LeetCode:LeetcodeC++/Java

    Integer(atoi) 字符串转整数 string 13 Roman to Integer 罗马数字转整数 number,string 14 Longest Common Prefix 最长公共前缀 string 16 3Sum Closest 最接近的三数之和 two pointers,array 21 Merge Two Sorted ...

    leetcode小白刷题-String-to-Integer-atoi-:来自https://leetcode.com/problems/st

    leetcode小白刷题字符串到整数 (atoi) 示例 1: Input: " 42 " Output: 42 示例 2: Input: " -42 " Output: - 42 Explanation: The first non-whitespace character is ' - ' , which is the minus sign. Then take...

    leetcode2sum-Problems:编程问题的回购

    leetcode 2sum # Programming-Problems This will have many problems from all over the web, As of ...LeetCode: ...Integer ...String To Integer Atoi [Medium] LC9: Palindrome Number [Easy] LC11:

    LeetCode最全代码

    * [String](https://github.com/kamyu104/LeetCode#string) * [Linked List](https://github.com/kamyu104/LeetCode#linked-list) * [Stack](https://github.com/kamyu104/LeetCode#stack) * [Queue]...

    leetcode2sumc-leetcode:JavaScript版本leetcode中文版代码

    String to Integer (atoi) 中等 9 Palindrome Number 简单 11 Container With Most Water 中等 12 Integer to Roman 中等 13 Roman to Integer 简单 14 Longest Common Prefix 简单 15 3Sum 中等 16 3Sum Closest ...

    leetcode双人赛-LeetCode:力扣笔记

    leetcode双人赛LeetCode 编号 题目 难度 题型 备注 Two Sum 简单 Add Two Numbers 中等 链结串列 重要 Longest Substring Without Repeating Characters 中等 字串 重要 Median of Two Sorted Arrays 困难 数学 ...

    leetcode分类-Leetcode:cpp中的Leetcode解决方案(已解决424个)

    leetcode 分类 Leetcode 总结 (updating) # Title Solution 1 Two ...用unordered_map,降至O(n) ...一个变量存储进位,当l1,l2,进位非均为空时,继续计算 ...注意要保证n1长度小于n2,因为...String to Integer (atoi) 9 Palind

    leetcode338-LeetCode:LeetCode刷题总结

    LeetCode刷题总结 1.Two Sum 2.Add Two Numbers 3.Longest Substring Without Repeating Characters 4.Median of Two Sorted Arrays 5.Longest Palindromic Substring (Manacher算法待完成) 6.ZigZag Conversion 7....

    leetcode530-algorithm:算法

    String to Integer (atoi) 009 Palindrome Number 010 Regular Expression Matching 011 Container With Most Water 012 Integer to Roman 013 Roman to Integer 014 Longest Common Prefix 015 3Sum 016 3Sum ...

    leetcode中国-leetcode:leetcode刷题

    String to Integer (atoi) addBinary longestPalindrome maximal rectangle :dp问题,较难 largestRectangleArea 求直方图的最大面积,左右两次扫面+剪枝优化 Valid Parentheses 用栈判断括号匹配 Regular ...

    分割数组求最大差值leetcode-Leetcode-Road:LeetCode刷题记录

    学习之路 记录自己完成LeetCode的代码和结果。 序号 中文名称 英文名称 通过率 难度 1 Two Sum 47.0% 简单 2 Add Two Numbers 36.0% 中等 3 Longest Substring Without Repeating Characters 32.0% 中等 4 Median of...

    javalruleetcode-lxxcode:Leetcode或Lintcode的代码

    String to Integer (atoi) (java, javascript) leetcode 9: 回文数(java, javascript) leetcode 10:正则表达式匹配(java) leetcode 11:盛水的容器(java) leetcode 12:整数转罗马(java) leetcode 13:罗马到...

    leetcode316-leetcode_script:leetcode题解更新脚本

    String to Integer (atoi) Easy -&gt; Medium 19 Remove Nth Node From End of List Easy -&gt; Medium 33 Search in Rotated Sorted Array Hard -&gt; Medium 35 Search Insert Position Medium -&gt; Easy 36

    leetcode题库-LeetCode-Go:用GO回答LeetCode

    leetcode题库 LeetCode-Go 理论基础 见Note 脑图 TODO 待填充 算法题 面试高频出现,以及一些非常经典重要的算法题优先 题目列表 ...Integer ...(atoi) 15.5% Medium 0009 Palindrome Number 49.4% Easy

    leetcode答案-leetcode:leetcode问题解决方案

    leetcode 答案 Leetcode题解 leetcode题库的答案及解决思路,随着解题的深入,题解会不断改进时间复杂度和空间复杂度,因此每个题包含多个算法。 目录 Algorithms(算法) ...String to Integer (atoi) Medium com.bc

    leetcode跳跃-LeCode:乐科

    两数之和 2. Add Two Numbers 两数相加 3. Longest Substring Without Repeating Characters 无重复字符的最长子串 4. Median of Two Sorted Arrays 寻找两个有序数组的中位数 5. Longest Palindromic Substring ...

    leetcode卡-LeetCode:LeetCode题解

    Integer(atoi) :star: :star: :star: 注意细节,溢出 ---- strlen :star: :star: :star: const char,size_t类型 ---- strcpy :star: :star: :star: 字符串复制,返回值,赋值语句 0028 strStr :star: :star: :star:...

    Coding Interview In Java

    19 String to Integer (atoi) 59 20 Merge Sorted Array 61 ... ... 231 Counting Bits 561 232 Maximum Product of Word Lengths 563 233 Gray Code 565 234 Permutations 567 235 Permutations II 571 236 ...

Global site tag (gtag.js) - Google Analytics