How to work with leading zeros in integers

自古美人都是妖i 提交于 2019-11-28 12:14:16
falsetru

A numeric literal that starts with 0 is an octal representation, except the literals that start with 0x which represent hexadecimal numbers or 0b which represent binary numbers.

1 * 8**2 + 1 * 8**1 + 2 * 8**0 == 74

To convert it to 0112, use String#% or Kernel#sprintf with an appropriate format string:

'0%o' % 0112  # 0: leading zero, %o: represent as an octal
# => "0112"

You can't, because Ruby's Integer class does not store leading zeros.

A leading 0 in a number literal is interpreted as a prefix:

  • 0 and 0o: octal number
  • 0x: hexadecimal number
  • 0b: binary number
  • 0d: decimal number

It allows you to enter numbers in these bases. Ruby's parser converts the literals to the appropriate Integer instances. The prefix or leading zeros are discarded.

Another example is %w for entering arrays:

ary = %w(foo bar baz)
#=> ["foo", "bar", "baz"]

There's no way to get that %w from ary. The parser turns the literal into an array instance, so the script never sees the literal.

0112 (or 0o112) is interpreted (by the parser) as the octal number 112 and turned into the integer 74.

A decimal 0112 is just 112, no matter how many zeros you put in front:

0d0112   #=> 112
0d00112  #=> 112
0d000112 #=> 112

It's like additional trailing zeros for floats:

1.0   #=> 1.0
1.00  #=> 1.0
1.000 #=> 1.0

You probably have to use a string, i.e. "0112"

Another option is to provide the (minimum) width explicitly, e.g.:

def descending_order(number, width = 0)
  sprintf('%0*d', width, number).reverse.to_i
end

descending_order(123, 4)
#=> 3210

descending_order(123, 10)
#=> 3210000000
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!