0

I'm trying to research this simple operation, and I'm coming up with nothing for it. I want to be able to find a place value for an integer, and I'm wondering if there is a specific gem or operation for it. For example:

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

So far the best I have been able to do is come up with this ugly little function:

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

Is there a more elegant way of finding a place value?

4

3 回答 3

5

Convert the integer to a string and then get the character in the nth position.

a.to_s[5] #=> '8'
于 2013-04-30T18:29:19.697 回答
4

If you don't want to resort to strings then you could use

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

If you wanted the answer in a different base, then pass the extra argument:

value_at_position(1651684651,5) #=> 8
value_at_position(1651684651,5,8) #=> 3, since 1651684651 is 14234532453 in base 8
于 2013-04-30T18:52:44.483 回答
2

I agree with @Charles' technique, but I think you're considering a "place" as 1-indexed from the right rather than 0-indexed from the left. Inconveniently, your example number and desired output leave that ambiguous. In case my hunch is right, here's an elaboration on Charles' technique that would do what you want:

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
于 2013-04-30T18:49:04.947 回答