外部輸入一個字串,若開頭為數字的話或 +-
符號的話則轉換為 int
的型態,且若超過 int
的最大或最小值則取極限值為準。
我的第一版答案如下:
public class Solution { public int MyAtoi(string str) { var arrNum = "0123456789".ToList(); var arrSymbol = "-".ToList(); if (string.IsNullOrWhiteSpace(str)) { return 0; } else { str = str.Trim(); } bool isFirstAddSymbol = (str[0] == '+'); if (isFirstAddSymbol) { str = str.Substring(1); } if (string.IsNullOrWhiteSpace(str)) { return 0; } bool isFirstNum = (arrNum.IndexOf(str[0]) != -1); bool isFirstSymbol = (arrSymbol.IndexOf(str[0]) != -1); if ((isFirstAddSymbol && isFirstSymbol) || (!isFirstNum && !isFirstSymbol) || (isFirstSymbol && str.All(x => arrNum.IndexOf(x) == -1)) || (isFirstSymbol && str.Length > 1 && (arrNum.IndexOf(str[1]) == -1))) { return 0; } string numString = string.Empty; str = isFirstSymbol ? str.Substring(1) : str; for (int i = 0; i < str.Length; i++) { bool isNum = (arrNum.IndexOf(str[i]) != -1); if (!isNum) { break; } if (numString == "0") { numString = str[i].ToString(); } else { numString += str[i].ToString(); } } int maxValueLength = int.MaxValue.ToString().Length; long ans = int.MaxValue; bool isMoreMax = (numString.Length > maxValueLength) || (long.Parse(numString) > int.MaxValue); if (!isMoreMax) { ans = long.Parse(numString); } if (isFirstSymbol && isMoreMax) { ans += 1; } return Convert.ToInt32(isFirstSymbol ? -ans : ans); } }
參考最佳解答後的優化版:
public class Solution { public int MyAtoi(string str) { str = (str ?? string.Empty).Trim(); if (string.IsNullOrWhiteSpace(str)) { return 0; } bool isMinusSign = (str[0] == '-'); if (isMinusSign || (str[0] == '+')) { if ((str.Length == 1) || ((str.Length > 1) && (str[1] < '0' || str[1] > '9'))) { return 0; } str = str.Substring(1); } string numString = string.Empty; foreach (var item in str) { bool isNum = (item >= '0' && item <= '9'); if (!isNum) { break; } if (numString == "0") { numString = item.ToString(); } else { numString += item.ToString(); } } if (numString == string.Empty) { return 0; } int maxValueLength = int.MaxValue.ToString().Length; long ans = int.MaxValue; bool isMoreMax = (numString.Length > maxValueLength) || (long.Parse(numString) > int.MaxValue); if (!isMoreMax) { ans = long.Parse(numString); } if (isMinusSign && isMoreMax) { ans += 1; } return Convert.ToInt32(isMinusSign ? -ans : ans); } }