I'm stumped as to why my solution for the Recursive Digit Sum question on HackerRank is being rejected.
Background
The question:
For an input of string n and integer k, the number h is created by concatenating n "k" times. Find the "super digit" of h by recursively summing the integers until one is left.
For example:
- n = '9875', k = 2, so h = 98759875
- sum(98759875)= 58
- sum(58)= 13
- sum(13) = 4
Submissions
My Solution
def superDigit(n, k):
h=n*k
while len(h)>1:
h=str(sum([int(i) for i in h]))
return int(h)
Solution I've Found
def superDigit(n, k):
return 1 + (k * sum(int(x) for x in n) - 1) % 9
My Inquiry to the Community
What am I missing in my solution? Yes it's not as simple as the supplied solution involving the digital root function (which I don't fully understand, I just found it online) but I don't see how my function is supplying incorrect answers. It passes most of the test cases but is rejecting for 1/3 of them.
2条答案
按热度按时间rkue9o1l1#
这是我对你的案子的调查结果:
你不提供打字,所以我不得不检查一下,发现你用了一个
str
和一个int
。我怎么知道?如果使用2
str
s,乘法将失败:如果你使用2个
int
,h
也是一个int,那么你的sum
就会失败:因此,你必须有一个int和一个str。但这也不起作用,因为
int
*str
乘法使用的是连接,而不是“数学”加法:我的解决方案建议很简单:
1.使用键入以明确说明
1.使用
int
s进行乘法运算,使用str
s进行数字拆分只需编辑前两行即可完成此操作:
如果有帮助就告诉我。
ctrmrzij2#
多亏了@Tim Roberts、@Paul Hankin和@yagod的一些有用的评论,我才得以解决这个问题。事实上,这是因为超时!我所要做的就是更新一行:
h=str(sum([int(i) for i in n])*(k%9))