`
king_tt
  • 浏览: 2117292 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

【leetcode】String to Integer (atoi)

 
阅读更多

Question :

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.

Anwser 1 :

class Solution {
public:
    int atoi(const char *str) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        long long ret = 0;
        
        const char *p = str;
        
        while(*p == ' ') p++;
        
        bool valid = true;
        while(valid && *p == '+') {
            valid = false;
            p++;
        }
        
        while(*p == '0') p++;
        
        bool minus = false;
        if(*p == '-'){
            minus = true;
            p++;
        }
        
        while(*p != '/0'){
            if(*p >= '0' && *p <='9'){
                ret = ret * 10 + *p - '0';
                if(!minus && ret > INT_MAX) return INT_MAX; // positive and overflow
                if(minus && -ret < INT_MIN) return INT_MIN; // negative and overflow
                p++;
            } else {        // no digit then break
                break;
            }
        }
        
        return minus ? -ret : ret;
    }
};
注意点:

1) 结果变量 ret 设为了长整形(long long),防止溢出; 最后结果由长整形自动截取为整形(int),返回

2) 计算得到结果时,需要配合正负符号判断是否已经越界,越界溢出后直接返回


Anwser 2 :

class Solution {
 public:
     int atoi(const char *str) {
         // Start typing your C/C++ solution below
         // DO NOT write int main() function
         assert(str != NULL);
         
         while(isspace(*str)) str++;  // remove ' '
             
             
         int sign = (*str == '-') ? -1 : 1;
         
         if (*str == '-' || *str == '+')    // if can check one char
             str++;
             
         int ret = 0;
         while(isdigit(*str))   // is digit
         {
             int digit = *str - '0';
             
             if (INT_MAX / 10 >= ret)
                 ret *= 10;
             else
                 return sign == -1 ? INT_MIN : INT_MAX;
                 
             if (INT_MAX - digit >= ret)
                 ret += digit;
             else
                 return sign == -1 ? INT_MIN : INT_MAX;
                 
             str++;
         }
         
         return ret * sign;
     }
 };
注意点:

1) 结果类型为整形(int),不需要转化,非常好!

2) 对空格(‘ ’)、数字(isdigit)都直接调用函数,非常简洁!

3) 对溢出全部采用减法(-)判断,有效预防了加法运算可能的溢出问题,非常值得借鉴!


分享到:
评论

相关推荐

    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字符串转换为整数

    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中文版-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...

    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 困难 数学 ...

    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最全代码

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

    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

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

    String to Integer (atoi) 18.5% 中等 9 Palindrome Number 56.7% 简单 10 Regular Expression Matching 25.3% 困难 11 Container With Most Water 59.3% 中等 12 Integer to Roman 61.8% 中等 13 Roman to In

    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:乐科

    String to Integer (atoi) 字符串转换整数 (atoi) 9. Palindrome Number 回文数 10. Regular Expression Matching 正则表达式匹配 11. Container With Most Water 盛最多水的容器 12. Integer to Roman 整数转罗马...

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

    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:罗马到...

    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