8. String to Integer (atoi)
来源:互联网 发布:安卓 gba 模拟器 知乎 编辑:程序博客网 时间:2024/06/07 14:53
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
spoilers alert… click to show requirements for atoi.
public class Solution { public int myAtoi(String str) { // 1. null or empty string if (str == null || str.length() == 0) return 0; // 2. whitespaces str = str.trim(); // 3. +/- sign boolean positive = true; int i = 0; if (str.charAt(0) == '+') { i++; } else if (str.charAt(0) == '-') { positive = false; i++; } // 4. calculate real value double tmp = 0; for ( ; i < str.length(); i++) { int digit = str.charAt(i) - '0'; if (digit < 0 || digit > 9) break; // 5. handle min & max if (positive) { tmp = 10*tmp + digit; if (tmp > Integer.MAX_VALUE) return Integer.MAX_VALUE; } else { tmp = 10*tmp - digit; if (tmp < Integer.MIN_VALUE) return Integer.MIN_VALUE; } } int ret = (int)tmp; return ret; } }
阅读全文
0 0
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- Windows 安装 Anaconda3 详细过程
- hdfs架构的简述与hdfs读写策略
- 利用Hadoop计算FVC(植被覆盖度)思路
- 在做RTSP摄像机H5无插件直播中遇到的对接海康摄像机发送OPTIONS心跳时遇到的坑
- 值得推荐的C/C++框架和库
- 8. String to Integer (atoi)
- 动态规划入门 数字三角形
- Codeforces Round #382 (Div. 2) B. Urbanization【数据注意+贪心证明】
- building caffe with cudnn fails with undefined reference to `cudnnSetActivationDescriptor' error
- Apache YARN/Mesos与Google Borg差距多远?
- 排序
- JavaScript中数据类型详解
- PHP并行编程探索之三(定时异步)
- 2017 多校训练第六场 HDU 6097 Mindis