【Leetcode】8. String to Integer (atoi)
2016-12-11 21:42
393 查看
思路:
(1)去掉前后的空格。
(2)为防止溢出,result定义为long型,并定义flag标记正负数。
(2)依次判断每个字符,第一次遇到加号时,记flag为1;第一次遇到减号时,记flag为2;遇到数字时,存入result;否则直接break。
(3)若是负数,则需要result取反。
(4)若result超出最大正数,则返回Integer.MAX_VALUE;若result小于最小负数,则返回Integer.MIN_VALUE。
(5)强制转换后返回result。
Runtime: 42ms
(1)去掉前后的空格。
(2)为防止溢出,result定义为long型,并定义flag标记正负数。
(2)依次判断每个字符,第一次遇到加号时,记flag为1;第一次遇到减号时,记flag为2;遇到数字时,存入result;否则直接break。
(3)若是负数,则需要result取反。
(4)若result超出最大正数,则返回Integer.MAX_VALUE;若result小于最小负数,则返回Integer.MIN_VALUE。
(5)强制转换后返回result。
public class Solution { public int myAtoi(String str) { str = str.trim(); long result = 0; int flag = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (flag == 0 && str.charAt(i) == '+' ) flag = 1; else if (flag == 0 && str.charAt(i) == '-') flag = 2; else if (str.charAt(i) >= '0' && ch <= '9') { result = result * 10 + (ch - '0'); if (flag == 2 && result > Integer.MAX_VALUE) return Integer.MIN_VALUE; if (flag != 2 && result > Integer.MAX_VALUE) return Integer.MAX_VALUE; } else break; } if (flag == 2) result = -result; if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int)result; } }
Runtime: 42ms
相关文章推荐
- android DiskLruCache使用方法
- android studio 问题集
- Java添加中文到mysql乱码
- 20145325张梓靖 《信息安全系统设计基础》第13周学习总结
- 基础算法 01背包问题
- 查询几天以内的数据sql语句
- 基于用户的协同过滤(user-based collaborative filtering)
- 分享asp.net 网站部署一段时候后无法响应经验
- 389. Find the Difference#2(Done)
- 学习内容
- 《高胜算交易策略》读书笔记
- 50. Pow(x, n)
- 神经网络与深度学习(3):Backpropagation算法
- Linux电源管理-Runtime PM
- 1080. Graduate Admission (30)
- 郝斌的C语言基础 165,166 枚举
- CentoOS更换yum源
- [SSH]如何敲一条线
- 走进阿里,从提高自身开始
- 【工具】让开发更高效-Firefox Developer Edition