[LeetCode] String to Integer (atoi)
来源:互联网 发布:冯大辉 知乎 编辑:程序博客网 时间:2024/05/29 18:20
题目
https://leetcode.com/problems/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.
代码
1047 / 1047 test cases passed.Runtime: 15 ms
#define rint register intsigned int MAX = 0x7fffffff;signed int MAX_MINUS = 0x80000000;int myAtoi(char* str) { if (str == NULL) { return 0; } rint offset = 0; while (str[offset] == ' ' || str[offset] == '\t') { offset++; } int minus = 0; if (str[offset] == '+') { offset++; } else if (str[offset] == '-') { offset++; minus = 1; } long val = 0; // 可能超出int,所以用long for (rint i = offset; str[i] != '\0'; i++) { if (str[i] >= '0' && str[i] <= '9') { val = val * 10 + str[i] - '0'; if (val > MAX) {//及时退出 break; } } else { break; } } if (minus) { val = val *(-1); } //printf("%ld\n", val); if (val > MAX) { val = MAX; } if (val < MAX_MINUS) { val = MAX_MINUS; } return val;}
附:一些输入值
阅读全文
0 0
- LeetCode:String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- LeetCode String to Integer(atoi)
- LeetCode :String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- Leetcode : String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- LeetCode-String to Integer (atoi)
- [leetcode] String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- 【leetcode】String to Integer (atoi)
- LeetCode - String to Integer (atoi)
- LeetCode: String to Integer (atoi)
- Leetcode: String to Integer (atoi)
- [LeetCode] String to Integer (atoi)
- leetcode String to Integer (atoi)
- [LeetCode]String to Integer (atoi)
- java遍历map的五种方法
- 在Linux上安装Intellij IDEA
- Python操作nosql数据库
- [POJ] 3278 Catch That Cow
- 《弃子长安》第六章 九煞夺命
- [LeetCode] String to Integer (atoi)
- 编译原理之词法分析
- C语言:假设在n进制下,等式成立,567*456=150216,n的值是多少?
- java.io中的read方法详解(尤其在数组流即在ByteArrayInputStream中)
- 三分钟学会使用log4J
- java基础知识总结
- WeaveSocket框架-Unity太空大战游戏-概述0
- httpclient4.5获取和设置cookie
- How does HDR relate to color space and bit depth?