user3002211
user3002211

Reputation: 183

How to find the sum of elements on even position?

How to find the sum of elements on even position without usage of arrays etc, only normal operations?

For example: 159

Sum = 5.

159120

Sum = 5+1+0 = 6.

My work:

int sumofdigits(int x)
{
    int sum = 0;
    while(x > 0){
        if (x % 100 != 0)
            sum += x % 100;
        x /= 100;
    }
    return sum;
}

Upvotes: 2

Views: 2752

Answers (4)

khajvah
khajvah

Reputation: 5090

Well simple modification should do the trick.

int main()
{
    int x = 1549;
    //Get the number of digits
    int length = snprintf(NULL, 0, "%i", x);
    int sum = 0;
    while(x > 0){
        if (x % 100 != 0) {
            //check if the number of digits is even to start from the last digit
            if (length % 2 == 0) {
                sum += x % 10;
                x /= 10; 
            }
            else {
                x /= 10;
                sum += x % 10;
            }

            x /= 10;
        }
    }
   cout << sum << endl; 

   return 0;
}

EDIT: Solved the problem/bug in the algorithm. This might not be the best answer but I didn't want to completely write a different one(than the answer before edit).

Upvotes: 1

ScarletAmaranth
ScarletAmaranth

Reputation: 5101

int accumulateIfEvenPos(int num, int pos) {
    if (num == 0) return 0;
    int digit = num % 10;
    int next = num / 10;
    return pos & 1 ? digit + accumulateIfOdd(next, ++pos) : accumulateIfOdd(next, ++pos);
}

You call it with pos 1 initially - demo here.

Upvotes: 1

godel9
godel9

Reputation: 7400

Since you're counting "even" digits from the left, you first need to count the number of digits in order to know whether the least significant digit is even or not:

int sumOfEvenDigits(int x)
{
    // First, count the number of digits
    int digitCount = 0;
    int tmp = x;
    while(tmp) {
        tmp /= 10;
        digitCount++;
    }

    // If the number of digits is odd, throw away the least significant digit
    if(digitCount % 2 == 1)
        x /= 10;

    // Keep adding the least significant digit, and throwing away two digits until you're done.
    int sum = 0;
    while(x){
        sum += x % 10;
        x /= 100;
    }
    return sum;
}

Upvotes: 2

Thomas Matthews
Thomas Matthews

Reputation: 57749

You will need to have an index variable that keeps track of the position:

unsigned int digit_position = 0;
while (x > 0)  
{  
  unsigned int digit_value = x % 10;
  if (digit_position is even)
  {
     // Add digit_value to sum
  }
  // Shift value right one digit
  x /= 10;
  ++digit_position;
}

There may be other methods using a position variable and the pow() function. But that is left as an exercise for the reader.

Upvotes: 0

Related Questions