Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding digits at Even and Odd Places (C#)

Tags:

c#

algorithm

I need to add the digits on the even and odd places in an integer. Say, Let number = 1234567. Sum of even place digits = 2+4+6 = 12 Sum of odd place digits = 1+3+5+7 = 16

Wait, don't jump for an answer!

I'm looking for codes with minimal lines, preferably one-line codes. Similar to what 'chaowman' has posted in the thread Sum of digits in C#.

Does anyone has some cool codes. Thanks.

like image 559
abhilashca Avatar asked Aug 24 '09 09:08

abhilashca


2 Answers

    bool odd = false;

    int oddSum = 1234567.ToString().Sum(c => (odd = !odd) ? c - '0' : 0 );

    odd = false;

    int evenSum = 1234567.ToString().Sum(c => (odd = !odd) ? 0 : c - '0' );
like image 184
Ed Guiness Avatar answered Sep 27 '22 01:09

Ed Guiness


It's not a one-liner, but the following works:

int oddSum = 0, evenSum = 0;
bool odd = true;
while (n != 0) {
    if (odd)  
        oddSum += n % 10;
    else
        evenSum += n % 10;
    n /= 10;
    odd = !odd;
}

EDIT:

If you want it on one line:

int oddSum = 0, evenSum = 0; bool odd = true; while (n != 0) { if (odd) oddSum += n % 10; else evenSum += n % 10; n /= 10; odd = !odd; }
like image 45
Patrick McDonald Avatar answered Sep 27 '22 01:09

Patrick McDonald