1. 程式人生 > >劍指offer:第49題字串轉化成整型(題目要求:不要用轉換函式)

劍指offer:第49題字串轉化成整型(題目要求:不要用轉換函式)

思路:拆分在合併,有非數字符號的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; } }