"Algorithm" string to int
Encountered an interview problem, at that time only wrote a train of thought, now give concrete realization, is a kind of more stupid realization Way
Public classStringtoint {/// <summary> ///implement string conversion to int yourself/// </summary> /// <param name= "str" ></param> /// <returns></returns> Public Static intToInt (stringstr) { if(string. Isnullorwhitespace (str))//empty string directly returns 0 { return 0; } BOOLIsminus =false;//whether it is a negative number intresult =0;//return Results for(inti =0; I < Str. Length; i++) { intnum =ToInt (Str[i]); if(num = =-1)//not a number . { return 0; } if(num = =-2)//a negative case { if(i = =0)//Yes, negative .{Isminus=true; } Else //negative sign in middle of string { return 0; } } checked //Check Arithmetic overflow{result+ = Totens (num, str. Length-i-1); } } returnIsminus?0-Result:result; } /// <summary> ///Convert char to int, note-(negative), cannot turn return-1, negative number returns-2/// </summary> /// <param name= "C" ></param> /// <returns></returns> Private Static intToInt (Charc) {Switch(c) { Case '1': return 1; Case '2': return 2; Case '3': return 3; Case '4': return 4; Case '5': return 5; Case '6': return 6; Case '7': return 7; Case '8': return 8; Case '9': return 9; Case '0': return 0; Case '-': return-2; } return-1; } /// <summary> ///get the corresponding number based on the number of digits/// </summary> /// <param name= "i" ></param> /// <param name= "index" ></param> /// <returns></returns> Private Static intTotens (intIintindex) { if(I <=0) { return 0; } for(intj =0; J < Index; J + +) {i= i *Ten; } returni; } }
"Algorithm" string to int