-
-
Save havenwood/4074170 to your computer and use it in GitHub Desktop.
A simple atoi function in ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A simple translate from a string to integer. | |
# A minus before all numbers will be consider to be a negative number. | |
def atoi(str) | |
return str if !str.is_a? String | |
fixed_str = fix(str) | |
result = 0 | |
fixed_str.each_char do |c| | |
result = result*10 + c.to_i | |
end | |
fixed_str[0]=='-' ? -result : result | |
end | |
def fix(str) | |
minus = false | |
str = str.split('.').first | |
#Consider a minus symbol before all numbers as a negative number. | |
str.each_char do |c| | |
minus = true if c == '-' | |
break if( c>='0' && c<='9') | |
end | |
str.each_char do |c| | |
str.delete!(c) if(c<'0' || c>'9') | |
end | |
minus ? "-#{str}" : str | |
end | |
atoi('123').should == 123 | |
atoi('-af+240.sf').should == -240 | |
atoi(';sf2.34-34').should == 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment