We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Use a carry value initialized to 0. When you see carry+input is odd, you count 2 loaves and set the carry to 1. If carry+input is instead even, set carry to 0.
After all the input is read, if the carry value from the last input is 1, the problem is insoluble, so you output NO, otherwise output the number of loaves counted.
int loaves = 0;
int carry = 0;
while ( N-- ) {
int i;
cin >> i;
if ( (carry + i)%2 ) {
loaves += 2;
carry = 1;
} else
carry = 0;
}
if ( carry )
cout << "NO" << endl;
else
cout << loaves << endl;
or simpler still:
while ( N-- ) {
int i;
cin >> i;
carry = (carry + i)%2;
loaves += 2*carry;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Fair Rations
You are viewing a single comment's thread. Return to all comments →
It's simpler than that.
Use a carry value initialized to 0. When you see carry+input is odd, you count 2 loaves and set the carry to 1. If carry+input is instead even, set carry to 0.
After all the input is read, if the carry value from the last input is 1, the problem is insoluble, so you output NO, otherwise output the number of loaves counted.
or simpler still: