This question is still about Integer processing. I mentioned in the Reverse Integer question that the focus of this question is not the problem itself, but the handling of the corner case. integers generally have two points, one is the problem of positive and negative symbols, and the other is the problem of integer out-of-bounds. The idea is simple: Remove unnecessary space characters and then read the symbols (note that both positive and negative numbers are possible, or there may be no symbols). Then, read the numbers in order, there are three conditions for the end condition: (1) The exception character appears (according to the C language standard, the exception character is truncated and the previous part is retained as the result); (2) number out of bounds (returns the nearest integer); (3) string ends. The Code is as follows:
public int atoi(String str) { if(str==null) { return 0; } str = str.trim(); if(str.length()==0) return 0; boolean isNeg = false; int i = 0; if(str.charAt(0)=='-' || str.charAt(0)=='+') { i++; if(str.charAt(0)=='-') isNeg = true; } int res = 0; while(i
'9') break; int digit = (int)(str.charAt(i)-'0'); if(isNeg && res>-((Integer.MIN_VALUE+digit)/10)) return Integer.MIN_VALUE; else if(!isNeg && res>(Integer.MAX_VALUE-digit)/10) return Integer.MAX_VALUE; res = res*10+digit; i++; } return isNeg?-res:res;}
This question mainly deals with integer processing. Note that this question has been mentioned above, because it is a basic problem of C language and may still occur during the interview, which is relatively low-level, edge situations are critical, and tester interviews may be more common.