有没有更好的方法来求数字的乘法和
本文关键字:数字 更好 方法 有没有 | 更新日期: 2023-09-27 18:18:13
int N = 2345;
var digitArray = N.ToString().ToCharArray();
int multiplicationSum = 1;
foreach (char digit in digitArray)
{
multiplicationSum = int.Parse(digit.ToString()) * multiplicationSum;
}
var sum = 0;
var sumArray = multiplicationSum.ToString().ToCharArray();
foreach (char digit in sumArray)
{
sum = int.Parse(digit.ToString()) + sum;
}
谢谢
假设你不需要处理负数,似乎用数学方法处理会更有意义
int N = 2345;
int multiplicationSum = 1;
while(N!=0)
{
multiplicationSum = multiplicationSum * (N%10);
N = N/10;
}
var sum = 0;
while(multiplicationSum!=0)
{
sum = sum + (multiplicationSum%10);
multiplicationSum = multiplicationSum/10;
}
引用:
%运算符
%操作符计算第一个操作数除以第二个
后的余数
/接线员:
两个整数相除,结果总是整数。例如,7/3的结果是2