gpt4 book ai didi

ruby - 我可以用什么代替 char.to_i?

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:46 26 4
gpt4 key购买 nike

对于一项作业,我需要编写一个名为 get_integer_from_string 的方法,它将输入字符串转换为整数。我已经完成了,但有一个要求:

  • 请不要使用隐式或自动类型转换来解决这个问题问题,即 C 中的 atoi(),Python 中的 int(),函数类似于 parseInt()在 Java 中或在 PHP 中为 intval()

我可以在下面的代码中用什么替换 char.to_i 来满足这个要求?

def get_integer_from_string(str, based=7)
return 0 if (/^(?<num>\d+)$/ =~ str).nil?
result = 0
str.reverse.each_char.with_index do |char, index|
tmp = char.to_i * based**index
result += tmp
end
result rescue 0
end

最佳答案

我怀疑你想多了。由于 char 只能是十个不同的字符串之一,只需将查找表作为散列即可:

C_TO_I = {
"0" => 0, "1" => 1, "2" => 2, "3" => 3,
"4" => 4, "5" => 5, "6" => 6, "7" => 7,
"8" => 8, "9" => 9
}

然后只需将代码中的 char.to_i 替换为 C_TO_I[char]。演示:

char = "7"
p C_TO_I[char]
# => 7

关于ruby - 我可以用什么代替 char.to_i?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38299436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com