Atoiは、文字列を整数に変換するためにJavaで実装されています。



Atoi Is Implemented Java Convert String An Integer



分析

この問題については、次のことを考慮する必要があります。



1. null or empty string 2. white spaces 3. +/- sign 4. calculate real value 5. handle min & max

Javaソリューション

public int atoi(String str) { if (str == null || str.length() < 1) return 0 //Trim whitespace str = str.trim() char flag = '+' //Check for negative or positive numbers int i = 0 if (str.charAt(0) == '-') { flag = '-' i++ } else if (str.charAt(0) == '+') { i++ } //Use double to store the result double result = 0 //Calculated while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') { result = result * 10 + (str.charAt(i) - '0') i++ } if (flag == '-') result = -result //Maximum and minimum handle if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE return (int) result }

画像