lintcode:String to Integer II
2016-04-03 18:11
405 查看
Implement function
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.
Have you met this question in a real interview?
Example
Tags
atoito convert a string to an integer.
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.
Have you met this question in a real interview?
Example
"10" => 10 "-1" => -1 "123123123123123" => 2147483647 "1.0" => 1
Tags
class Solution { public: /** * @param str: A string * @return An integer */ int atoi(string str) { // write your code here if (str.size() == 0) return 0; int idx = 0; while (idx < str.size()) if (str[idx] != ' ') break; else idx++; bool negativeFlag = false; if (str[idx] == '+') { idx++; } else if (str[idx] == '-') { idx++; negativeFlag = true; } double result = 0; //非常重要; while (idx < str.size() && str[idx] >='0' && str[idx] <= '9') { result = result*10 + (str[idx]-'0'); idx++; } if (negativeFlag) result = -1 * result;//这里需要先计算负数 if (result > INT_MAX) return INT_MAX; if (result < INT_MIN) return INT_MIN; return (int)result; } };
相关文章推荐
- Android 编码规范
- 确定一个字符串的所有字符全都不同算法实现
- 分析Linux内核创建一个新进程的过程
- Java单例模式
- 使用Redis分布式队列
- POJ 3468 A Simple Problem with Integers 【树状数组】
- #通过一道阿里笔试题加深对JVM的理解
- Java Arrays.sort源代码解析
- 工厂模式
- 在NodeJS中玩转Protocol Buffer
- Java初始化3
- ubuntu下 rc.local的脚本不运行
- 【linux】记一次httpd服务正常,http不能访问的惨痛教训
- Design_pattern之单例模式
- java.io.Serializable浅析
- linux内核启动过程追踪
- jQuery代码优化:事件委托篇
- ASP.Net后台 实现先弹出对话框,再跳转到另一个网页的实现方法
- Dubbo基本原理机制(优秀推荐)
- UVa 12563 - Jin Ge Jin Qu hao(类01背包,白书)