gpt4 book ai didi

ruby - 查找 Kaprekar 的电话号码

转载 作者:太空宇宙 更新时间:2023-11-03 18:14:27 25 4
gpt4 key购买 nike

我正在研究 Kaprekar 号码的问题 https://rubymonk.com/learning/books/1-ruby-primer/problems/150-kaprekar-s-number .我在这里展示的代码之前已经讨论过,但我对另一个方面感兴趣。练习要求:

Find if a given number is a Kaprekar number.

练习下面有一个解决方案(参见解决方案),看起来像这样:

def kaprekar?(k)
no_of_digits = k.to_s.size
square = (k ** 2).to_s

second_half = square[-no_of_digits..-1]
first_half = square.size.even? ? square[0..no_of_digits-1] : square[0..no_of_digits-2]

k == first_half.to_i + second_half.to_i
end

在练习下面还有一个提示(需要提示吗?):

Use Fixnum.to_s to convert the number into a string to do digit operations. Use String.to_i to convert back to integer.

我有几个问题,谁能解释一下:

1)为什么要把数字转成字符串才能进行数字运算?

2) 在 second_half 变量中,我知道 -(减号)是正方形的背面,但它是什么意思:-1?它必须是左侧 (first_half) n 或 n-1 位数字,而不是 second_half。或者它是结束引号,因为我们将数字转换为字符串?

3) 为什么 first_half 变量中有 2 个问号 - 在“even”之后和“square”之前?

最佳答案

1) why it is need to convert the number into a string to do digit operations?

因为你必须得到下半场:

second_half = square[-no_of_digits..-1]

这里处理string比较方便。这将返回最后一个 no_of_digits,例如

'1234'[-2..-1] # => '34'

-2..-1range数字的数量,并且不可能直接获得一系列整数位置。

in the second_half variable i understand that - (minus) sign is the back side of the square, but what does it mean: -1? it must be left side (first_half) n or n-1 digits and not second_half. or is it ending quotation mark, because we converted the number into a string?

-1 是最后一个元素。即

'1234'[-1] # => 4

类似地,-n 是从最后一个元素开始的第 n 个,其中 n 是某个整数

3) why is 2 question marks in first_half variable - after 'even' and before 'square'?

第一个问号是方法名的一部分。按照惯例,返回 bool 值的方法应该以问号结尾。请注意 kaprekar? 也不异常(exception)。

第二个是三元条件运算符的一部分。它看起来如下:

boolean_expression ? true_expression : false_expression

first_half 要么是 square[0..no_of_digits-1] 如果 square 中的字符数是偶数,要么是 square[0.. no_of_digits-2]否则

关于ruby - 查找 Kaprekar 的电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28436497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com