[题目] Implement atoi to convert a string to an integer.

[题目解析] 该题目比较常见,从LeetCode上看代码通过率却只有13.7%,于是编码提交,反复修改了三四次才完全通过。该题目主要需要考虑各种测试用例的情况,比如"+5"、"   67"、"   +0078"、"  12a56--"、int的最大值最小值溢出等情况,通过这个题目,联系到实际项目中,我们一定要多考虑边界情况,各种输入的情况,确保代码健壮性。

 1    public int myAtoi(String str) {
 2        if(null == str || 0 == str.length()) return 0;
 3        str = str.trim();  //剔除无效字符
 4        char first = str.charAt(0);
 5        if(str.length() == 1 && !Character.isDigit(first)) return 0; //无效字符返回0,比如"+"
 6        boolean isNeg = (first == '-'); //判断第一个字符是否为负号
 7        int idx = isNeg ? 1 : 0;
 8        if(first == '+') idx = 1;
 9        while(str.charAt(idx) == '0'){ //把最前面的0去掉
10         idx++;
11        }
12        int result = 0;
13        while(idx < str.length()){
14         char ch = str.charAt(idx);
15         if(!Character.isDigit(ch)) break; //如果遇到非数字字符,则终止循环,返回已经计算的数字
16         int num = ch - '0'; //char字符转化成对应数字
17         if(isNeg && result > Integer.MAX_VALUE/10) return Integer.MIN_VALUE; //检测整数是否溢出的情况
18         if(isNeg && result == Integer.MAX_VALUE/10 && num > 8) return Integer.MIN_VALUE;
19         if(!isNeg && result > Integer.MAX_VALUE/10) return Integer.MAX_VALUE;
20         if(!isNeg && result == Integer.MAX_VALUE/10 && num > 7) return Integer.MAX_VALUE;
21         result = result * 10 + num;
22         idx++;
23        }
24        return isNeg?(-result):result;
25    }

我们不妨来分析下java自带的string转化为int的方法,我们发现有Integer.valueOf()和Integer.parseInt()两个方法,我们进入方法去看。

public static Integer valueOf(String s) throws NumberFormatException {

return Integer.valueOf(parseInt(s, 10));

}

public static int parseInt(String s) throws NumberFormatException {

return parseInt(s,10);

}

我们发现这两个方法都调用了同一个方法parseInt(s,10),那么我们来分析这个方法就可以了。

   public static int parseInt(String s, int radix)throws NumberFormatException{/** WARNING: This method may be invoked early during VM initialization* before IntegerCache is initialized. Care must be taken to not use* the valueOf method.*/if (s == null) {throw new NumberFormatException("null");}if (radix < Character.MIN_RADIX) { //radix参数指定转化为几进制的数throw new NumberFormatException("radix " + radix +" less than Character.MIN_RADIX");}if (radix > Character.MAX_RADIX) {throw new NumberFormatException("radix " + radix +" greater than Character.MAX_RADIX");}int result = 0;boolean negative = false;int i = 0, len = s.length();int limit = -Integer.MAX_VALUE;int multmin;int digit;if (len > 0) {char firstChar = s.charAt(0);if (firstChar < '0') { // Possible leading "+" or "-"if (firstChar == '-') {negative = true; //为负数limit = Integer.MIN_VALUE;} else if (firstChar != '+') //如果第一个字符不是数字也不是‘+’、‘-’符号,则抛出格式异常throw NumberFormatException.forInputString(s);if (len == 1) // Cannot have lone "+" or "-"throw NumberFormatException.forInputString(s);i++;}multmin = limit / radix;while (i < len) {// Accumulating negatively avoids surprises near MAX_VALUEdigit = Character.digit(s.charAt(i++),radix); //转化成对应数字if (digit < 0) {throw NumberFormatException.forInputString(s);}if (result < multmin) {throw NumberFormatException.forInputString(s);}result *= radix;if (result < limit + digit) {throw NumberFormatException.forInputString(s);}result -= digit;} //计算出来是负数} else {throw NumberFormatException.forInputString(s);}return negative ? result : -result; }

  

转载于:https://www.cnblogs.com/zzchit/p/5808476.html

[LeetCode] NO. 8 String to Integer (atoi)相关推荐

  1. LeetCode算法入门- String to Integer (atoi)-day7

    LeetCode算法入门- String to Integer (atoi)-day7 String to Integer (atoi): Implement atoi which converts ...

  2. 【细节实现题】LeetCode 8. String to Integer (atoi)

    LeetCode 8. String to Integer (atoi) Solution1:我的答案 参考链接:http://www.cnblogs.com/grandyang/p/4125537. ...

  3. Kotlin实现LeetCode算法题之String to Integer (atoi)

    题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 1 clas ...

  4. LeetCode 8. String to Integer (atoi)(字符串)

    LeetCode 8. String to Integer (atoi)(字符串) LeetCode 8 String to Integer atoi字符串 问题描述 解题思路 参考代码 By Sca ...

  5. 乘风破浪:LeetCode真题_008_String to Integer (atoi)

    乘风破浪:LeetCode真题_008_String to Integer (atoi) 一.前言 将整型转换成字符串,或者将字符串转换成整型,是经常出现的,也是必要的,因此我们需要熟练的掌握,当然也 ...

  6. String to Integer (atoi) leetcode java

    题目: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input ca ...

  7. 008 String to Integer (atoi) [Leetcode]

    题目内容: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input ...

  8. leetcode 8. String to Integer (atoi)

    也许是我没有理解清楚题意,为什么输入+-2的时候要输出0,而不是输出2呢. public class Solution {public int myAtoi(String str) {if(str = ...

  9. 8. String to Integer (atoi)

    题目: Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input ca ...

最新文章

  1. ERROR: Unable to load class 'org.gradle.api.internal.component.Usage'.
  2. 团队作业——Alpha冲刺 6/12
  3. poj2774 sa模版
  4. errors_impl.InvalidArgumentError: Input to reshape is a tensor
  5. 离线地图解决方案(二):地图基本控制
  6. 408. Valid Word Abbreviation有效的单词缩写
  7. 2017.10.6 单词 思考记录
  8. android-studio于java相关
  9. java:Eclipse插件springsource-tool-suite的下载和安装
  10. Magento(CE1.X)自带模块解析一
  11. Json-getJSON
  12. fv-15php1c 安装图,SQLite - C/C++接口 API(一)
  13. vue 生成二维码(中间logo),下载二维码,复制链接(vue + vue-qr+clipboard)
  14. Kaggle——TMDB 5000 Movie Dataset电影数据分析
  15. 关于H5调用摄像头麦克风的权限问题
  16. 示波器探头的 x1x10衰减、补偿校准手法
  17. 防盗系统Java_java小区防盗报警系统
  18. 游戏开发中的数学基础
  19. 流量焦虑意外带来契机,“福禄控股们”赚钱容易做大难?
  20. python编码使用ascii编码_Python中的编码问题:ASCII码 Unicoden编码 UTF-8编码

热门文章

  1. 7-35 部落 (10 分)
  2. PAT乙级 1093 字符串A+B(两种解法)
  3. IDEA社区版找不到tomcat
  4. spring boot—默认日志框架配置
  5. decose oracle_ORACLE会话连接进程三者总结
  6. c语言有啥简单的小程序,c语言-简单小程序-简单算法
  7. 矩形键盘 linux,基于ARM的矩阵键盘设计及其linux驱动实现
  8. mysql数据库插入datetime_往MySQL数据库datetime类型字段中插入数据库的当前时间
  9. cf1114 D. Flood Fill
  10. php array_key_exists() 与 isset() 的区别