在红宝石中找到位置值

时间:2013-04-30 18:24:29

标签: ruby math

我正在尝试研究这个简单的操作,而我却没有为它做任何事情。我希望能够找到一个整数的位置值,我想知道是否有特定的宝石或操作。例如:

a = 1651684651
p find_place_value_of(a,5) # imaginary function to return the value of the
                           #  number in the 10000 column
                           #  output should be 8

到目前为止,我能做的最好的事情就是想出这个丑陋的小功能:

j= 262322
a= j 
a/=100000 
b= j - a*100000
b/=10000 
c= j - a*100000 - b*10000 
c/=1000 
d= j - a*100000 - b*10000 - c*1000 
d/=100 
e= j - a*100000 - b*10000 - c*1000 - d*100
e/=10 
f= j - a*100000 - b*10000 - c*1000 - d*100 - e*10
p a,b,c,d,e,f,j

是否有更优雅的方式来寻找地方价值?

3 个答案:

答案 0 :(得分:5)

将整数转换为字符串,然后在第n个位置获取字符。

a.to_s[5] #=> '8'

答案 1 :(得分:4)

如果您不想使用字符串,那么可以使用

def value_at_position(number, position, base=10)
  (number % (base**position))/(base**(position-1))
end

如果你想在不同的基础上得到答案,那么传递额外的论点:

value_at_position(1651684651,5) #=> 8
value_at_position(1651684651,5,8) #=> 3, since 1651684651 is 14234532453 in base 8

答案 2 :(得分:2)

我同意@Charles的技巧,但我认为你正在考虑从右边开始索引的“地点”而不是左边的0索引。不方便的是,您的示例数字和所需的输出会使这种模糊不清。如果我的预感是正确的,这里是查尔斯技术的详细说明,可以做你想做的事情:

def find_place_value_of(num, place)
  num.to_s.reverse[place-1].to_i
end

a = 1651684651
p find_place_value_of(a, 5) # => 8
p find_place_value_of(a, 4) # => 4