1

I need to make a program that calculates the factorial of a number and sums the different numbers.

I'm stuck at the point where I need to take the current number in the for loop to do it's factorial (e.g. the number 145 and I can't take the 5). I've tried the following:

for (int i = length-1; i >= 0; i--)
{
    int currentNumber = inputString[i];
    currentSum = currentSum * i;
    sum += currentSum;
}

inputString is the length of the given number. The problem is that in this way currentNumber becomes the ascii equivalent (if i = 3 currentSum becomes 51). How do I make currentSum become 3?

1
  • int currentNumber = inputString[i] - '0'; Commented Sep 23, 2019 at 7:46

3 Answers 3

4

Alternatively you could use:

int currentNumber = int.Parse(inputString[i].ToString());
Sign up to request clarification or add additional context in comments.

1 Comment

int.Parse only accepts string values, not char, this will result in a compile error unless you add .ToString() to inputString[i]
2

I'd like to suggest an alternative:

int num = int.Parse(inputString); // Convert whole input to int
int sum = 0;

while( num != 0 ) // >0 is not enough, num could be negative.
{
    sum += num % 10;  // Sum up least significant place
    num = num / 10;   // "Decimal shift right"
}

With your example "145" this would mean:

Iteration 1:
sum += 145 % 10 => sum = 0 + 5 = 5
num = num / 10 => num = 145 / 10 = 14

Iteration 2:
sum += 14 % 10 => sum = 5 + 4 = 9
num = num / 10 => num = 14 / 10 = 1

Iteration 3:
sum += 1 % 10 => sum = 9 + 1 = 10
num = num / 10 => num = 1 / 10 = 0

num == 0 => end while , sum = 10

Disclaimer: This assumes, the input is in fact a valid integer value. I'd strongly suggest to validate that, first. "Never trust user input."

Comments

1

Assuming inputString is numeric only, you can get away with:

int currentNumber = inputString[i] - '0';

Short explanation: character representation of number '3' is 51, but they are in order (so '0' is 48, '1' is 49, etc.) and you can get the "numerical value" of a character by removing the offset (which is the value of '0').

2 Comments

This worked like a charm. I'll be using this method until my knowledge becomes enough to come up with my own. Thank you!
+1 for clever and reasonably readable. I would suggest commenting this code with a small explanation of what exactly is happening, something along the lines of // Converting char ASCII value to int value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.