使用ruby生成代表数字的字母? [英] Generate letters to represent number using ruby?

查看:90
本文介绍了使用ruby生成代表数字的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个字母序列,即与数字相对应的字母"A","DE","GJE"等.前26个非常简单,因此3将返回"C",26将返回"Z",而27将返回"AA",28将返回"AB",依此类推.

I would like to generate a sequence of letters i.e. "A", "DE" "GJE", etc. that correspond to a number. The first 26 are pretty easy so 3 returns "C", 26 returns "Z", and 27 would return "AA", 28 "AB", and so on.

我不太想知道的是如何执行此操作,以便它可以处理传入的任何数字.因此,如果传入4123,我应该取回3个字母的某种组合,因为(26 * 26 * 26)允许最多+17,000个组合.

The thing I can't quite figure out is how to do this so it will handle any number passed in. So if I pass in 4123 I should get back some combination of 3 letters since (26 * 26 * 26) allows for up to +17,000 combinations.

有什么建议吗?

推荐答案

class Numeric
  Alph = ("a".."z").to_a
  def alph
    s, q = "", self
    (q, r = (q - 1).divmod(26)); s.prepend(Alph[r]) until q.zero?
    s
  end
end

3.alph
# => "c"
26.alph
# => "z"
27.alph
# => "aa"
4123.alph
# => "fbo"

这篇关于使用ruby生成代表数字的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆