1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package com.demo.s8;
import java.util.HashMap;
public class Solution { public int myAtoi(String s) { HashMap<String, String[]> map = new HashMap(); map.put("start", new String[]{"start", "signed", "number", "end"}); map.put("signed", new String[]{"end", "end", "number", "end"}); map.put("number", new String[]{"end", "end", "number", "end"}); map.put("end", new String[]{"end", "end", "end", "end"}); String step = "start"; long num = 0; int sign = 1; for(int i = 0;i < s.length() && !step.equals("end"); i++) { char ch = s.charAt(i); int n = getChar(ch); step = map.get(step)[n]; if("number".equals(step)) { num = num * 10 + (ch - '0'); num = sign == 1 ? Math.min(num, (long)Integer.MAX_VALUE) : Math.min(num, -1 * (long)Integer.MIN_VALUE); } else if("signed".equals(step)) { sign = (ch == '+') ? 1 : -1; } else if("signed".equals(step)) { return 0; } } return sign * (int)num;
}
private int getChar(char ch) { if(' ' == ch) { return 0; } else if('+' == ch || '-' == ch) { return 1; } else if(0 <= ch-'0' && ch-'0' <= 9) { return 2; } else { return 3; } } }
|