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.
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' );
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With