【发布时间】:2018-01-26 17:08:07
【问题描述】:
我有这个代码:
public class Kata
{
public static bool Narcissistic(int value)
{
//add variale to hold final result
int finalResult = 0;
//get the length of the value input
int valLength = value.ToString().Length;
//convert value given into an array of ints
string valString = value.ToString();
//iterate over each number and multiply that number by the length of value input
for (int i=0; i < valLength; i++) {
//convert char at index[i] of stringified value to int and mutiply by # of digits, store to result
finalResult += int.Parse(valString[i]) * valLength;
}
//return the result
return finalResult == value;
}
}
我在运行时遇到错误,我理解,但不知道如何解决。我的目标是取一个数字(即 1234)并将每个数字乘以它包含的总位数(即 1*4 + 2*4 + 3*4...等)。
【问题讨论】:
-
无法读取未格式化为代码的代码
-
你在int和string之间来回转换一堆,为什么?您得到的确切错误/问题是什么?
-
如果您使用
%10获取最低有效数字并使用/10截断最低有效数字,则可以完全避免使用该字符串。 -
感谢我的 +1 让我们熟悉 narcissistic numbers 的概念:它不应该是位数而不是 * 长度的幂吗?