Find the sum of digits of a number at even and odd places - GeeksforGeeks

22 Jun, 2021
Given a number N, the task is to find the sum of digits of a number at even and odd places.
Examples: 
Input: N = 54873 Output: Sum odd = 16 Sum even = 11
Input: N = 457892 Output: Sum odd = 20 Sum even = 15  
Approach:  
First, calculate the reverse of the given number.
To the reverse number we apply modulus operator and extract its last digit which is actually the first digit of a number so it is odd positioned digit.
The next digit will be even positioned digit, and we can take the sum in alternating turns.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the reverse of a numberint reverse(int n){    int rev = 0;    while (n != 0) {        rev = (rev * 10) + (n % 10);        n /= 10;    }    return rev;} // Function to find the sum of the odd// and even positioned digits in a numbervoid getSum(int n){    n = reverse(n);    int sumOdd = 0, sumEven = 0, c = 1;     while (n != 0) {         // If c is even number then it means        // digit extracted is at even place        if (c % 2 == 0)            sumEven += n % 10;        else            sumOdd += n % 10;        n /= 10;        c++;    }     cout << "Sum odd = " << sumOdd << "\n";    cout << "Sum even = " << sumEven;} // Driver codeint main(){    int n = 457892;    getSum(n);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG {     // Function to return the reverse of a number    static int reverse(int n)    {        int rev = 0;        while (n != 0) {            rev = (rev * 10) + (n % 10);            n /= 10;        }        return rev;    }     // Function to find the sum of the odd    // and even positioned digits in a number    static void getSum(int n)    {        n = reverse(n);        int sumOdd = 0, sumEven = 0, c = 1;         while (n != 0) {             // If c is even number then it means            // digit extracted is at even place            if (c % 2 == 0)                sumEven += n % 10;            else                sumOdd += n % 10;            n /= 10;            c++;        }         System.out.println("Sum odd = " + sumOdd);        System.out.println("Sum even = " + sumEven);    }     // Driver code    public static void main(String args[])    {        int n = 457892;        getSum(n);    }} // This code is contributed by// Surendra_Gangwar
# Python3 implementation of the approach # Function to return the# reverse of a numberdef reverse(n):    rev = 0    while (n != 0):        rev = (rev * 10) + (n % 10)        n //= 10    return rev # Function to find the sum of the odd# and even positioned digits in a numberdef getSum(n):     n = reverse(n)    sumOdd = 0    sumEven = 0    c = 1     while (n != 0):         # If c is even number then it means        # digit extracted is at even place        if (c % 2 == 0):            sumEven += n % 10        else:            sumOdd += n % 10        n //= 10        c += 1     print("Sum odd =", sumOdd)    print("Sum even =", sumEven) # Driver coden = 457892getSum(n) # This code is contributed# by mohit kumar
// C# implementation of the approachusing System; class GFG {     // Function to return the reverse of a number    static int reverse(int n)    {        int rev = 0;        while (n != 0) {            rev = (rev * 10) + (n % 10);            n /= 10;        }        return rev;    }     // Function to find the sum of the odd    // and even positioned digits in a number    static void getSum(int n)    {        n = reverse(n);        int sumOdd = 0, sumEven = 0, c = 1;         while (n != 0) {             // If c is even number then it means            // digit extracted is at even place            if (c % 2 == 0)                sumEven += n % 10;            else                sumOdd += n % 10;            n /= 10;            c++;        }         Console.WriteLine("Sum odd = " + sumOdd);        Console.WriteLine("Sum even = " + sumEven);    }     // Driver code    public static void Main()    {        int n = 457892;        getSum(n);    }} // This code is contributed by// Akanksha Rai
<?php// PHP implementation of the above approach // Function to return the reverse of a numberfunction reverse($n){    $rev = 0;    while ($n != 0)    {        $rev = ($rev * 10) + ($n % 10);        $n = floor($n / 10);    }    return $rev;} // Function to find the sum of the odd// and even positioned digits in a numberfunction getSum($n){    $n = reverse($n);    $sumOdd = 0; $sumEven = 0; $c = 1;     while ($n != 0)    {         // If c is even number then it means        // digit extracted is at even place        if ($c % 2 == 0)            $sumEven += $n % 10;        else            $sumOdd += $n % 10;                     $n = floor($n / 10);        $c++;    }     echo "Sum odd = ", $sumOdd, "\n";    echo "Sum even = ", $sumEven;} // Driver code$n = 457892;getSum($n); // This code is contributed by Ryuga?>
<script> //JavaScript implementation of the approach     // Function to return the    // reverse of a number    function reverse(n) {    let rev = 0;    while (n != 0) {        rev = (rev * 10) + (n % 10);        n = Math.floor(n / 10);    }    return rev;}       // Function to find the sum of the odd    // and even positioned digits in a number    function getSum(n) {        n = reverse(n);        let sumOdd = 0, sumEven = 0, c = 1;         while (n != 0) {         // If c is even number then it means        // digit extracted is at even place        if (c % 2 == 0)            sumEven += n % 10;        else            sumOdd += n % 10;        n = Math.floor(n / 10);        c++;    }      document.write("Sum odd = " + sumOdd);    document.write("<br>");    document.write("Sum even = " + sumEven);}      let n = 457892;      // function call      getSum(n); // This code is contributed by Surbhi Tyagi </script>
Sum odd = 20
Sum even = 15
 
Another approach: The problem can be solved without reversing the number. We can extract all the digits from the number one by one from the end. If the original number was odd then the last digit must be odd positioned else it will be even positioned. After processing a digit, we can invert the state from odd to even and vice versa.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the sum of the odd// and even positioned digits in a numbervoid 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, 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;} // Driver codeint main(){    int n = 457892;    getSum(n);     return 0;}
// Java implementation of the above approachclass GFG{     // Function to find the sum of the odd// and even positioned digits in a numberstatic void getSum(int n){         // If n is odd then the last digit    // will be odd positioned    boolean isOdd = (n % 2 == 1) ? true : false;     // To store the respective sums    int sumOdd = 0, 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;    }    System.out.println("Sum odd = " + sumOdd);    System.out.println("Sum even = " + sumEven);} // Driver codepublic static void main(String[] args){    int n = 457892;    getSum(n);}} // This code is contributed by jrishabh99
# Python3 implementation of the approach # Function to find the sum of the odd# and even positioned digits in a numberdef getSum(n):     # If n is odd then the last digit    # will be odd positioned    if (n % 2 == 1) :        isOdd = True    else:        isOdd = False     # To store the respective sums    sumOdd = 0    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 = not isOdd         # Remove last digit        n //= 10         print( "Sum odd = " , sumOdd )    print("Sum even = " ,sumEven) # Driver codeif __name__ =="__main__":    n = 457892    getSum(n) # This code is contributed by chitranayal
// C# implementation of the above approachusing System; class GFG{     // Function to find the sum of the odd// and even positioned digits in a numberstatic 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, 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;    }    Console.WriteLine("Sum odd = " + sumOdd);    Console.Write("Sum even = " + sumEven);} // Driver code   static public void Main (){    int n = 457892;         getSum(n);}} // This code is contributed by offbeat
<script> // Javascript implementation of the approach // Function to find the sum of the odd// and even positioned digits in a numberfunction getSum(n){     // If n is odd then the last digit    // will be odd positioned    let isOdd = (n % 2 == 1) ? true : false;     // To store the respective sums    let sumOdd = 0, 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 = Math.floor(n/10);    }     document.write("Sum odd = " + sumOdd + "<br>");    document.write("Sum even = " + sumEven);} // Driver code      let n = 457892;    getSum(n);  // This code is contributed by Mayank Tyagi </script>
Sum odd = 20
Sum even = 15
 
Convert the integer to string. Traverse the string and store all even indices sum in one variable and all odd indices sum in another variable.
Convert the integer to string. Traverse the string and store all even indices sum in one variable and all odd indices sum in another variable.
Below is the implementation:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the sum of the odd// and even positioned digits in a numbervoid getSum(int n){         // To store the respective sums    int sumOdd = 0, sumEven = 0;     // Converting integer to string    string num = to_string(n);     // Traversing the string    for(int i = 0; i < num.size(); i++)    {        if (i % 2 == 0)            sumOdd = sumOdd + (int(num[i]) - 48);        else            sumEven = sumEven + (int(num[i]) - 48);    }    cout << "Sum odd = " << sumOdd << "\n";    cout << "Sum even = " << sumEven << "\n";} // Driver codeint main(){    int n = 457892;    getSum(n);         return 0;} // This code is contributed by souravmahato348
// Java implementation of the approach  import java.util.*;  class GFG{  static void getSum(int n){    // To store the respective sum    int sumOdd = 0;    int sumEven = 0;      // Converting integer to String    String num = String.valueOf(n);      // Traversing the String    for(int i = 0; i < num.length(); i++)        if (i % 2 == 0)            sumOdd = sumOdd + (num.charAt(i) - '0');        else            sumEven = sumEven + (num.charAt(i) - '0');      System.out.println("Sum odd = " + sumOdd);    System.out.println("Sum even = " + sumEven);}  // Driver codepublic static void main(String[] args){    int n = 457892;    getSum(n);}} // Code contributed by swarnalii
# Python3 implementation of the approach # Function to find the sum of the odd# and even positioned digits in a numberdef getSum(n):     # To store the respective sums    sumOdd = 0    sumEven = 0         # Converting integer to string    num = str(n)         # Traversing the string    for i in range(len(num)):        if(i % 2 == 0):            sumOdd = sumOdd+int(num[i])        else:            sumEven = sumEven+int(num[i])     print("Sum odd = ", sumOdd)    print("Sum even = ", sumEven)  # Driver codeif __name__ == "__main__":    n = 457892    getSum(n) # This code is contributed by vikkycirus
// C# implementation of the approachusing System; class GFG{ static void getSum(int n){         // To store the respective sum    int sumOdd = 0;    int sumEven = 0;     // Converting integer to String    String num = n.ToString();     // Traversing the String    for(int i = 0; i < num.Length; i++)        if (i % 2 == 0)            sumOdd = sumOdd + (num[i] - '0');        else            sumEven = sumEven + (num[i] - '0');     Console.WriteLine("Sum odd = " + sumOdd);    Console.WriteLine("Sum even = " + sumEven);} // Driver codepublic static void Main(){    int n = 457892;    getSum(n);}} // This code is contributed by subhammahato348
<script>// Javascript implementation of the approach function getSum(n){    // To store the respective sum    let sumOdd = 0;    let sumEven = 0;       // Converting integer to String    let num = (n).toString();       // Traversing the String    for(let i = 0; i < num.length; i++)        if (i % 2 == 0)            sumOdd = sumOdd + (num[i] - '0');        else            sumEven = sumEven + (num[i] - '0');       document.write("Sum odd = " + sumOdd+"<br>");    document.write("Sum even = " + sumEven+"<br>");} // Driver codelet n = 457892;getSum(n); // This code is contributed by unknown2108</script>
Output: 
Sum odd = 20
Sum even = 15
mohit kumar 29
ankthon
SURENDRA_GANGWAR
Akanksha_Rai
KajalKasat
ukasp
jrishabh99
offbeat
surbhityagi15
mayanktyagi1709
vikkycirus
souravmahato348
swarnalii
unknown2108
subhammahato348
number-digits
Greedy
Mathematical
School Programming
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Fractional Knapsack Problem
Activity Selection Problem | Greedy Algo-1
Coin Change | DP-7
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays