剑指Offer_49_把字符串转换成整数

题目描述

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
输入例子:
+2147483647
        1a33
输出例子:
2147483647
        0

解题思路

遍历字符串,首先判断第一位是否为+,-,如果是,则跳过。计算后面的字符串表达的数字。

实现

public class Solution {
    public int StrToInt(String str) {
        if (str == null || str.length() <= 0) return 0;
        int index = 0;
        int ch = 1;
        if (str.charAt(0) == '+' || str.charAt(0) == '-'){
            index = 1;
            if (str.charAt(0) == '-') ch = -1;
        }
        int sum = 0;
        for (int i = index; i < str.length(); i++){
            if (str.charAt(i) < '0' || str.charAt(i) > '9') return 0;
            sum = sum * 10 + (str.charAt(i) - '0');
        }
        return sum*ch;
    }

    public static void main(String[] args) {
        System.out.println(new Solution().StrToInt("123"));
    }
}
posted @ 2016-08-26 10:29  峰扬迪  阅读(130)  评论(0编辑  收藏  举报