题解 | #将字符串转化为整数#
将字符串转化为整数
http://www.nowcoder.com/practice/44d8c152c38f43a1b10e168018dcc13f
import java.util.*; public class Solution { /** * * @param str string字符串 * @return int整型 */ public int atoi (String str) { // write code here int sign = 1; boolean has = false; int ans =0, pop = 0; for(int i = 0; i < str.length(); ++i) { if(str.charAt(i) == '-' && !has) { sign = -1; has = true; continue; } if(str.charAt(i) == '+' && !has) { sign = 1; has = true; continue; } if(str.charAt(i) == ' ' && !has) { continue; } if(str.charAt(i) >= '0' && str.charAt(i) <= '9') { has = true; pop = str.charAt(i) - '0'; if(ans * sign > Integer.MAX_VALUE / 10 || ans * sign == Integer.MAX_VALUE / 10 && pop * sign > 7) { return Integer.MAX_VALUE; } if(ans * sign < Integer.MIN_VALUE / 10 || ans * sign == Integer.MIN_VALUE / 10 && pop * sign < -8) { return Integer.MIN_VALUE; } ans = ans * 10 + pop; }else{ return ans * sign; } } return ans * sign; } }