剑指offer50题(把字符串转换成整数)
2018-01-08 10:23
766 查看
题目:将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
思路:把字符串的数字转换成整数,注意有无符号数的边界问题(上溢出、下溢出)即可。
代码:
思路:把字符串的数字转换成整数,注意有无符号数的边界问题(上溢出、下溢出)即可。
代码:
public class Solution { public int StrToInt(String str) { if(str == null || str.length()==0) return 0; int start; int tag; if(str.charAt(0)=='+'){ start=1; tag=1; } else if(str.charAt(0)=='-'){ start=1; tag=0; } else{ start=0; tag=1; } long result = 0; for(int i=start;i<str.length();i++){ char temp = str.charAt(i); if(temp>='0' && temp<='9'){ result = result*10+(temp-'0'); if(tag==1 && result>Integer.MAX_VALUE) throw new RuntimeException("上溢出"); if(tag==0 && result<Integer.MIN_VALUE) throw new RuntimeException("下溢出"); } else{ return 0; } } if(tag==0){ return (int)(-1*result); } else{ return (int)result; } } }
相关文章推荐
- 剑指offer 50 把字符串转换成整数
- 【剑指offer-解题系列(50)】把字符串转换成整数
- 【剑指offer】C语言:实现函数可以将一个字符串转换为对应的整数,如+1234输出1234
- 剑指Offer学习总结-把字符串转换成整数
- 剑指offer - 面试题49:把字符串转换为整数
- 剑指offer-把字符串转换为整数
- 剑指offer-----将一个字符串转换成对应的整数(模拟atoi)
- 剑指Offer - 九度1508 - 把字符串转换成整数
- [剑指offer][面试题49]把字符串转换成整数(待完善)
- 【剑指Offer学习】【面试题49:把字符串转换成整数】
- 剑指offer题解 把字符串转换成整数(todo:考虑大整数的情况)
- 剑指Offer:面试题49 把字符串转换成整数
- 剑指offer——字符串转换为整数
- 剑指offer 面试题49 把字符串转换成整数
- 剑指offer(46)-把字符串转换成整数
- 剑指offer 49. 把字符串转换成整数
- 剑指offer之字符串到整数的转换,例如输入字符串12345,输出整数12345.
- 【剑指Offer面试编程题】题目1508:把字符串转换成整数--九度OJ
- 剑指offer——面试题:把字符串转换为整数
- 把字符串转换成整数 剑指offer