【算法】String To Integer
来源:互联网 发布:mac照片图库文件夹 编辑:程序博客网 时间:2024/05/21 10:36
题目要求:
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.
这是LeetCode中的第8题,剑指offer中涉及到的一道面试题,将String转化为Integer型,看似很简单,但是需要考虑的情况很多,需要比较细心。
首先字符串转换中遇见非数字字符的处理,字符串超出最大整型和最小整型怎么处理。开题遇到空格,用trim()去空格。+,-号只可能在去空格后第一位。中间遇到非数字字符,直接返回前一段字符,判断是否有效,并转换为整型。
代码如下:
/*** 将字符串转化为整数* @congrisheng* @2017-3-12*/public static int StrToInt(String str){ /*定义最大最小边界值*/ int max = Integer.MAX_VALUE; int min = Integer.MIN_VALUE; if(str == null || str.length() == 0){ return 0; } /*去掉字符串首尾的空格*/ str = str.trim(); /*如果首位是+,- 作为整数的符号*/ boolean sign = false; if(str.charAt(0) == '-' || str.charAt(0) == '+'){ if(str.charAt(0) == '-'){ sign = true; } str = str.substring(1); } int len = str.length(); /*定义为long型去储存结果*/ long res = 0; for(int i = 0; i < len; i++){ char s = str.charAt(i); /*不是整数就中断*/ if(s < '0' || s > '9'){ break; } /*转换*/ res = res*10 + (s - '0'); /*超过阈值直接return*/ if(!sign && res > max){ return max; } if(sign && -res < min){ return min; } } if(sign){ res = -res; } /*转换为int型的数*/ return (int)res;}
From 《剑指offer》 Page12
0 0
- 【算法】String To Integer
- String to Integer 算法学习
- String to Integer算法实现
- String to Integer (atoi)算法
- 算法训练:String to Integer (atoi)
- LeetCode算法题目:String to Integer (atoi)
- String to Integer (atoi)(算法分析week6)
- string to integer & integer to string
- string to integer
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- [LeetCode]String to Integer
- 92:Container With Most Water
- 进程和线程
- IBInspectable和IBDesignable
- 最长串问题
- Bootstrap网页基础学习
- 【算法】String To Integer
- JAVA_最大公约数与最小公倍数
- Reflections中的getDeclared**与get**的区别
- Fighting_小银考呀考不过四级 递推
- Dubbo-入门指南+实例
- B-2
- 【知识整理】Hibernate-HQL查询之分页查询、投影查询、报表查询
- Retrofit解析网页Json数据简单实例
- JAVA_哥德巴赫猜想的证明