【剑指Offer】将字符串转化为整数
2018-01-29 21:37
323 查看
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0思路分析
逐个字符判断,如果是数字字符,则继续,否则返回0.注意首字符有可能为 ‘+’、’-‘符号,特殊处理,并标记,返回的时候区分正负数。
代码实现
public class Solution { public static int StrToInt(String str) { if(str == null || str.length() == 0){ return 0; } int length = str.length(); int result = 0; boolean positive = true; for(int i=0; i < length; i++){ if(i == 0 && str.charAt(i) == '+'){ continue; } if(i == 0 && str.charAt(i) == '-'){ positive = false; continue; } if(!isDigit(str.charAt(i))){ return 0; } result = result * 10 + (str.charAt(i) - '0'); } return positive ? result : -result; } private static boolean isDigit(char num){ if(num >= '0' && num <= '9'){ return true; } return false; } public static void main(String[] args) { System.out.println(StrToInt("-123")); } }
相关文章推荐
- 【剑指Offer】面试题49:把字符串转化为整数
- 剑指offer43--字符串转化成整数
- 剑指offer----将字符串转化成整数
- 剑指offer 49. 把字符串转换成整数
- 剑指Offer-67:把字符串转换成整数
- 剑指offer:将字符串转化为整形
- 剑指offer面试题(49)把字符串转换成整数
- 【剑指Offer学习】【面试题49:把字符串转换成整数】
- 剑指offer 把字符串转换成整数
- 【剑指Offer面试编程题】题目1508:把字符串转换成整数--九度OJ
- 【剑指Offer面试编程题】题目1508:把字符串转换成整数--九度OJ
- LintCode-剑指Offer-(54)转换字符串到整数
- [剑指offer]把字符串转换成整数
- 【剑指offer】把字符串转换成整数
- 【剑指offer】题49:字符串转整数
- 【剑指offer】字符串转整数
- 剑指offer-字符串转化为数字
- 剑指Offer面试题49字符串转整数,面试题50二叉树两个结点的最低公共祖先
- 剑指offer - 面试题49:把字符串转换为整数
- 剑指offer | 训练题48:把字符串转换成整数