我正在尝试对数字的每个数字求平方,并返回一个包含所有平方值的整数。例如,如果输入的整数是9119,811181则将出来,因为9的平方是81,而1的平方是1。到目前为止,我的尝试是:
using System;
using System.Collections.Generic;
public class Kata
{
public static int SquareDigits(int n) {
String inputNums = n + "";
String[] digits = inputNums.Split("");
String outputNums = "";
foreach (string s in digits) {
int i = Int32.Parse(s);
var outputNum = (i * i);
outputNums += (outputNum);
}
return Int32.Parse(outputNums);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我不断收到此错误:
Test Failed
Expected: 811181
But was: 83156161
Run Code Online (Sandbox Code Playgroud)
谁能帮我了解我哪里出了问题?我试图将整数转换回字符串,以尝试将它们连接在一起,但未将它们加在一起,但是我似乎无法得出正确的值。我对C#还是比较陌生,因此可以提供任何帮助-谢谢:)
您可以通过执行数学运算来避免格式化和解析为字符串。
public static int SquareDigits(int n)
{
int result = 0;
int places = 0;
// loop while n has digits.
while(n > 0)
{
// Get the least significant digit
int digit = n % 10;
// Square the digit
int square = digit * digit;
// Add the square to the result the number of places over
result += (int)Math.Pow(10,places) * square;
// Increase the number of places by the size of the square (either 1 digit or 2)
places += square > 10 ? 2 : 1;
// Removed the least significant digit
n /= 10;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
注意:您可能要使用long而不是int返回类型,以便在遇到溢出之前允许使用更大的返回类型。甚至BigInteger处理所有可能的正int输入。同样很明显,对于任何负数,它都返回0。