纯暴力,用if语句把每种可能都列出来了 。代码比较臃肿:
class Solution { public int myAtoi(String s) { char []c = s.toCharArray(); int num = 0;//记录正负 int temp = 0;//判断0出现在数字之前还是数字中 long sum = 0;//解析后的值 int count = 0;//记录是否正确扫描到数字。 for (int i = 0; i < c.length; i++) { if (c[i]==' '){ if ((count == 0)&(num == 0)) { continue; } else { break; } } else if (c[i] == '-') { if ((num != 0)) { if (count ==1) { break; } else if (count == 0) { return 0; } } else { if (count == 0) { num = -1; continue; } else { break; } } } else if (c[i] == '+') { if ((num != 0)) { if (count ==1) { break; } else if (count == 0) { return 0; } } else { if (count == 0) { num = 1; continue; } else { break; } } } else if ((temp==0)&(c[i] == '0')) { count = 1; continue; } else if ((c[i] >= 48)&(c[i] <= 57)) { sum = (sum * 10) + (c[i]-48); temp = 1; count = 1; if (sum > Integer.MAX_VALUE){ sum = Integer.MAX_VALUE; if (num < 0) { return (int)(sum * (-1)-1); } else { return (int)sum; } } continue; } else { if(count == 0){ return 0; } else if ((temp == 0)& (count == 1)) { return 0; } else if ((count == 1)) { break; } } } if (num < 0) { return (int)sum * (-1); } else { return (int)sum; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)