ruby - Why does Rspec of RubyMonk says it true where the outcome is false? -
ruby - Why does Rspec of RubyMonk says it true where the outcome is false? -
i have this:
def kaprekar?(k) string_k = (k * k).to_s length_k = k.to_s.length.to_i length_k2 = string_k.to_s.length.to_i number1 = string_k[0...length_k].to_i number2 = string_k[length_k..length_k2].to_i number1 + number2 == k end
and according error message 297 output true.
returns true 297
rspec::expectations::expectationnotmeterror
expected false true
but when same on repl.it see output:
kaprekar?(297) string_k : 88209 length_k : 3 length2 : 5 number1 : 882 number2: 9 => false
which right answer.
can explain why rubymonk outcome true?
edit 1:the task is:
problem statement9 kaprekar number since 9 ^ 2 = 81 , 8 + 1 = 9
297 kaprekar number since 297 ^ 2 = 88209 , 88 + 209 = 297.
in short, kaprekar number k n-digits, if square , add together right n digits >to left n or n-1 digits, resultant sum k.
find if given number kaprekar number.
can explain why rubymonk outcome true?
rubymonk actually saying expected outcome true
, whereas implementation yields false
. edit states 297 is kaprekar number. reply clarify this.
quoth kaprekar's number rubymonk (emphasis mine):
for kaprekar number k n-digits, if square , add together the right n digits left n or n-1 digits, resultant sum k.
given k = 297
→ n = 3
→ k2 = 88,209
→ right n digits = 209
→ left n-1 digits = 88
→ 209 + 88 = 297
→ right n digits + left n-1 digits = k
∴ kaprekar?(297)
should homecoming true
.
your solution adds the left n digits (882), right n-1 (09), why false
(882 + 09 ≠ 297).
a sample solution, using array slicing negative indices, may like:
def kaprekar?(k) n = k.to_s.size square = (k * k).to_s right = square[-n..-1].to_i left = square[0...-n].to_i right + left == k end
ruby
Comments
Post a Comment