Multiply all even indexed integers by two

来源:互联网 发布:java中的类型转换 编辑:程序博客网 时间:2024/06/06 00:45

You can also multiply alternate numbers by 2

a = 4408041234567901

1.arr = a.to_s.chars.map.with_index {|n,i| i.even? ? n.to_i * 2 : n.to_i }# => [8, 4, 0, 8, 0, 4, 2, 2, 6, 4, 10, 6, 14, 9, 0, 1]

Improving a little bit, you can use a Hash to find the number to be multiplied.

2.h = {true => 2, false => 1}  a.to_s.each_char.map.with_index {|n,i| n.to_i * h[i.even?]}
3.coef = [2, 1].cycle
  a.to_s.each_char.map { |v| v.to_i * coef.next }
0 0
原创粉丝点击