剑指offer:第49题字符串转化成整型(题目要求:不要用转换函数)

来源:互联网 发布:最全金融网络理财产品 编辑:程序博客网 时间:2024/05/21 22:26
思路:拆分在合并,有非数字符号的return 0;public class _Test49 {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        String string = scanner.nextLine();        System.out.println(strToInt(string));    }    public static int strToInt(String string){        int result = 0;        if (string == null && string.isEmpty()) {            return 0;        }        int i = 0;        if (string.charAt(0) == '+'||string.charAt(0) == '-') {            i = 1;        }        for (; i < string.length(); i++) {            char c = string.charAt(i);            if (c <= '9' && c >= '0') {                int a = c - '0';                result = result * 10 + a;                            }            else{                return 0;            }        }        if (string.charAt(0) == '-') {            result = -result;        }                   return result;    }}
阅读全文
0 0