String to Integer (atoi)

来源:互联网 发布:安卓6.0源码多大 编辑:程序博客网 时间:2024/06/07 01:07

Implement atoi to convert a string to an integer.

题目解析:atoi函数 把字符串转为整型

思路解析:主要是考虑各种输入的 +123,-123 ,123,    123(空格),算是个比较简单的题目,直接上AC代码

 public int myAtoi(String str) {       // 安全性检查if (str.length() == 0 || str == null)return 0;// trim过滤空格str = str.trim();// 考虑正负数int i = 0;if (str.charAt(0) == '+')i++;if (str.charAt(0) == '-')i++;double resultNum = 0;while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {resultNum = resultNum * 10 + (str.charAt(i) - '0');i++;}// 输出结果if (str.charAt(0) == '-')resultNum = -resultNum;if (str.charAt(0) == '+') {if (resultNum > Integer.MAX_VALUE)return Integer.MAX_VALUE;}if (str.charAt(0) == '-') {if (resultNum < Integer.MIN_VALUE)return Integer.MIN_VALUE;}return (int)resultNum;    }


0 0