Given an integer N, determine whether it is even or odd.
Return "Even" if the number is divisible by 2, otherwise return "Odd".
Example 1
Input: n = 14
Output: Even
Explanation: 14 is divisible by 2 without any remainder, so it is an even number.
Example 2
Input: n = 17
Output: Odd
Explanation: 17 leaves remainder 1 when divided by 2, so it is an odd number.
Approach
The first observation is the whole key: even and odd numbers are decided only by what happens when the number is divided by 2.
The modulo operator % gives exactly the leftover part after division. So checking N % 2 is enough. If the remainder is 0, the number is even. Otherwise, it is odd.
Algorithm
Take the remainder when
Nis divided by2, because that remainder tells whether the number fits into exact pairs or not.If the remainder is
0, return"Even", since no value is left over after dividing by2.Otherwise, return
"Odd", because a non-zero remainder means one extra part is left behind.
Key Points
0is an even number because0 % 2 = 0.Negative numbers can also be even or odd. For example,
-8is even and-5is odd.
Dry Run
Check Even or Odd Dry Run
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: /* Returns "Even" if n is divisible by 2, otherwise returns "Odd". */ string checkEvenOdd(int n) { // A remainder of 0 means the number divides exactly by 2. if (n % 2 == 0) { return "Even"; } // Any non-zero remainder means the number is odd. return "Odd"; }};// Driver code startsint main() { int n = 17; Solution obj; cout << obj.checkEvenOdd(n) << endl; return 0;}Complexity Analysis
Time Complexity: O(1), because only one modulo check is performed.
Space Complexity: O(1), because no extra data structure is used.
Interview follow-up Questions
Because 0 is divisible by 2 without any remainder.
Be the first to add a comment.