0

I am currently trying to solve the hacker version of pset 1 (credit.c). I have successfully completed the rest of the psets (hacker and standard versions). I need to sum up the even (starting from 0) digits or alternate placing digits. E.g., given the number 5677, I need to have a program that will sum up 5 + 7 = 12, since they are even placing. The first digit is when i == 0.

My idea for this is to get an input from the user using:

Long n; 
n = GetLongLong(); 
int sum;

then using sprintf to convert my Long n into a string, s. After which, I can add the characters of the string (using s[i] for some i < strlen(s)) by using:

for (int i=0, i < strlen(s), i++)
{ 
    for (i % 2 == 0) 
        sum = sum + s[i]
}

But I don't know how to program this into the actual C language, especially the conversion from Long to Strings. Is my design of the program actually correct?

1

First, char is NOT int. I mean if you have

string s = "1234";

and then you wrote something like

int sum = 0;

// iterate over s and sum the chars up
for (int i = 0, n = strlen(s); i < n; i++)
{
    sum += s[i];
}

sum won't be 10!

Second, you have to start with the number's second-to-the-last digit. See this answer for more info!

Lastly, you may the remainder operator (i.e., %) to extract the digits of an int and either deal with them directly or store them in an int array and deal with them.

| improve this answer | |
0

That's because you are trying to add strings, and that's not the way it works. Easiest way it's using atoi function, from the stdlib library to convert from string to int:

my_int = atoi(my_string)

| improve this answer | |
0

Let's solve it together:

  1. We want to iterate over the digits, so let's iterate over a string and not a long. I found it easier to use cs50's GetString() inside a while and check if the input is composed out of digits (with the help of isdigit).
  2. You should start iterate from the end. So it makes sense to intial the i inside the loop to the last index of the string.
  3. We want to add up only odd digits, so our update statement should decrement i in two every step: for (int i = lastIndex; 0 <= i; i -= 2)
  4. We also need to remember that we deal with a string, hence each item in the string is a char. So in order to add up all the digit we need to cast every char to integer with the num[i] - '0' trick (every char is a number representing the char, so whatever the representation of '0' and the other digit is, the difference between them is the actual number).
| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .