2013-06-13 64 views
1
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; 
     } 

感謝有沒有更好的方法來找到數字乘法和求和?

+1

'var x = N%10'。 – Corak

回答

7

假設你不需要處理負數,似乎數學這樣做會使很多更有意義

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; 
} 

參考文獻:

% operator

%運算符的第二

/ operator將其第一個操作數計算後,將餘下的

當你把兩個整數,結果始終是整數。例如,7/3的結果是2

相關問題