Sum of even & odd

Easy
0/40
Average time to solve is 15m
profile
Contributed by
59 upvotes
Asked in company
Delta Air Lines

Problem statement

You are given an integer 'n'. Calculate the sum of even and odd digits of 'n', represented in decimals.


Even and odd do not refer to the position of the digit but to the polarity of the digit.


Return the answer in the form of an array of size 2, such that the 0th index represents the even sum and the 1st index represents the odd sum.


Example:
Input: 'n' = 1986.

Output: [14, 10]

Explanation: Even digits are 8 & 6, and odd digits are 1 & 9. The sum of even digits = 14, and the sum of odd digits = 10.
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first and only line of input contains the integer 'n'.
Output format :
The output consists of a single line containing two space-separated integers denoting the sum of even digits and the sum of odd digits, respectively.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.
Sample Input 1:
1234
Sample Output 1:
6 4
Explanation for Sample Input 1:
For the given input, the even digits are 2 and 4, and if we take the sum of these digits, we get 6 (2 + 4), and similarly, if we look at the odd digits, they are 1 and 3, which form a sum of 4 (1 + 3). 
Sample Input 2:
552245
Sample Output 2:
8 15

Explanation for Sample Output 2:

For the given input, the even digits are 2, 2, and 4, and if we take the sum of these digits, we get  8 (2 + 2 + 4), and similarly, if we look at the odd digits, they are, 5, 5 and 5 which form a sum of 15(5 + 5 + 5).

Expected time complexity:

The expected time complexity is O(log10(n)).
Constraints
 0 <= 'n' <= 10 ^ 9
Time Limit: 1 sec.
Hint

Try using basic mathematical operations.

Approaches (1)
Mathematical Operations

Use the modulo operation to find the digits of numbers.

 

Algorithm:

 

  • First, make an iteration till the given integer ‘num’ is greater than 0.
  • Store the one’s place digit in a variable.
  • Check whether the digit is even or odd
    • If the digit is even, add the digit in the ‘evenSum’.
    • If the digit is odd, add the digit in the ‘oddSum’.
  • Now, remove the one’s place digit from ‘num’.

 

Time Complexity

O(log10(n)), where ‘n' is the input integer.

 

Since we are iterating through all digits of the given input. 

 

Therefore, the overall time complexity will be O(log10(n)).

Space Complexity

O(1)

 

This approach uses constant space. 

 

Therefore, the overall space complexity will be O(1).

Code Solution
(100% EXP penalty)
Sum of even & odd
Full screen
Console