[英]Ruby to_s conversion to binary argument error
I was trying to solve a HackerRank problem which requires binary manipulation. 我试图解决需要二进制处理的HackerRank问题。 The test cases are extremely huge numbers so I thought better to manipulate them as strings.
测试用例非常庞大,因此我认为最好将它们作为字符串进行操作。
t=gets
def winner(pturn)
if a%2==0
puts "Richard\n"
else
puts "Louise\n"
end
end
while t != 0
turn=1
n=gets
(n2=n).to_s(2)
while n!=1
one="1"
zero="0"
if n2.count(1)>1
zero*=(n2.length - 2)
one.concat(zero)
n-=one.to_i(base=2)
else
n/=2
end
turn+=1
end
winner(turn)
t-=1
end
It caused an argument error (wrong number of argument) in line as seen below. 如下所示,它在一行中导致了一个参数错误(参数数量错误)。
(n2=n).to_s(2)
I think I'm using to_s
wrongly. 我认为我错误地使用了
to_s
。 I can't see the mistake and need someone to point it out. 我看不到错误,需要有人指出。
I think you are trying to convert a number in Ruby to a string with it's binary representation. 我认为您正在尝试将Ruby中的数字转换为其二进制表示形式的字符串。 This is possible with (if the number is actually a number in Ruby, eg Fixnum) :
这是可能的(如果数字实际上是Ruby中的数字,例如Fixnum):
4.to_s 2
# => "100"
But in your case, what you are getting after calling gets
is a string, and the to_s
method of the String class simply returns itself, and doesn't take any arguments, hence the error. 但是在您的情况下,调用
gets
之后gets
是一个字符串,而String类的to_s
方法只是返回自身,并且不接受任何参数,因此会出现错误。
You can fix it by calling gets.to_i
instead of just gets
, so the read string of contents will be converted to an integer in Ruby (you should be sure that you will only be reading numbers at there). 您可以通过调用
gets.to_i
而不是gets
来修复它,因此读取的内容字符串将在Ruby中转换为整数(您应该确保只在此处读取数字)。
And I believe you are trying to assign the binary representation (as a string) of n
into the variable n2
, for that you should be doing 我相信你想的分配二进制表示(字符串)
n
到变量n2
,对于自己应该做的
n2 = n.to_s(2)
If you just do : 如果您只是这样做:
(n2=n).to_s
Because of the parenthesis, first n2
will be assigned the value of n
, then to_s
will be called on n2
, the string version of n2
will be returned, and nothing else happens. 因为括号的,第一
n2
将被分配的值n
,然后to_s
将在名为n2
,串版本n2
将被退回,并没有什么事情发生。 First thing you should be doing is the conversion, then the assignment. 您应该做的第一件事是转换,然后是赋值。
And also you should pass in a string while calling String#count, ie you should call n2.count('2')
instead of n2.count(2)
. 而且,您还应该在调用String#count时传递一个字符串,即您应该调用
n2.count('2')
而不是n2.count(2)
。
Argument error is coming because you are trying to pass parameter to to_s method because to_s method never accept any arguments. 参数错误即将到来,因为您试图将参数传递给to_s方法,因为to_s方法从不接受任何参数。
So you should change (n2=n).to_s(2) to 所以你应该将(n2 = n).to_s(2)更改为
(n2=n).to_s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.