I am begginer,I am faced with a challenge to take few numbers and multiply the odd numbers in them to apply the lunhs alogrithm.
Ex- If user inputs 100034341341313413941391341393413. Is there any way I can take this input and specifically filter out the numbers in the odd places and even places and add them ?
Please just show me the way or how I can get it the number in a array and approach it.The rest i'll figure out.
Thanks in advance.
CodePudding user response:
Other approaches can be found in here.
void getSum(int n) {
// If n is odd then the last digit
// will be odd positioned
bool isOdd = (n % 2 == 1) ? true : false;
// To store the respective sums
int sumOdd = 0;
int sumEven = 0;
// While there are digits left process
while (n != 0) {
// If current digit is odd positioned
if (isOdd)
sumOdd = n % 10;
// Even positioned digit
else
sumEven = n % 10;
// Invert state
isOdd = !isOdd;
// Remove last digit
n /= 10;
}
cout << "Sum odd = " << sumOdd << "\n";
cout << "Sum even = " << sumEven;
}