C #

LeetCode: entier de conversion de chaîne (atoi) (c #)

Leetcode String Conversion Integer



Contenu du sujet

image
image

Code

public class Solution { public int MyAtoi(string str) { //Extract valid numeric symbol characters var numberStr = GetNumberStr(str) //Convert to numbers var number = GetNumber(numberStr) return number } /// /// convert to number /// /// number to be converted /// Converted numbers private int GetNumber(string numberStr) { if (numberStr.Length < 1) return 0 var minus = numberStr[0] == '-' //If the first digit is not a number, it must be at least 1 in length if (!char.IsNumber(numberStr[0]) && numberStr.Length < 2) return 0 if (!long.TryParse(numberStr, out var number)) return minus ? int.MinValue : int.MaxValue //Determine whether it exceeds the range if (number > 2147483647L) return int.MaxValue if (number < -2147483648L) return int.MinValue return (int)number } /// /// Extract valid numeric symbol characters /// /// string to be extracted /// Extracted numeric string private string GetNumberStr(string str) { var index = 0 //Get the position of the first valid character [+,-,0-9] while (str.Length > index && char.IsWhiteSpace(str[index])) index++ //If it exceeds the range or the first non-sign or number returns null if (str.Length <= index || (!char.IsNumber(str[index]) && str[index] != '-' && str[index] != '+')) return string.Empty var numberStrBuilder = new StringBuilder(str.Length) //Cyclically add consecutive numeric characters do { numberStrBuilder.Append(str[index]) index++ } while (str.Length > index && char.IsNumber(str[index])) //Build a numeric string return numberStrBuilder.ToString() } }