Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Checking Oddish and Evenish numbers - JavaScript
A number is Oddish if the sum of all of its digits is odd, and a number is Evenish if the sum of all of its digits is even.
We need to write a function that determines whether a number is Oddish or Evenish. The function should return true for Oddish values and false for Evenish values.
How It Works
The algorithm extracts each digit from the number, adds them up, and checks if the sum is odd or even:
- Extract digits using modulo (
num % 10) and integer division (Math.floor(num / 10)) - Sum all digits recursively
- Return
trueif sum is odd,falseif even
Example
const num = 434667;
const isOddish = (num, sum = 0) => {
if (num) {
return isOddish(Math.floor(num / 10), sum + (num % 10));
}
return sum % 2 === 1;
};
console.log(`Number: ${num}`);
console.log(`Is Oddish: ${isOddish(num)}`);
// Let's trace the digit sum for clarity
let testNum = 434667;
let digits = [];
let temp = testNum;
while (temp > 0) {
digits.push(temp % 10);
temp = Math.floor(temp / 10);
}
console.log(`Digits: ${digits.reverse().join(' + ')}`);
console.log(`Sum: ${digits.reduce((a, b) => a + b)}`);
Number: 434667 Is Oddish: false Digits: 4 + 3 + 4 + 6 + 6 + 7 Sum: 30
Testing Different Numbers
const testNumbers = [123, 456, 789, 111];
testNumbers.forEach(num => {
console.log(`${num} is ${isOddish(num) ? 'Oddish' : 'Evenish'}`);
});
123 is Evenish 456 is Oddish 789 is Evenish 111 is Oddish
Alternative Implementation
Here's a simpler iterative approach:
const isOddishSimple = (num) => {
let sum = 0;
while (num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
return sum % 2 === 1;
};
console.log(isOddishSimple(434667)); // false
console.log(isOddishSimple(123)); // false (1+2+3=6, even)
console.log(isOddishSimple(789)); // false (7+8+9=24, even)
console.log(isOddishSimple(111)); // true (1+1+1=3, odd)
false false false true
Conclusion
Both recursive and iterative approaches work effectively for determining Oddish vs Evenish numbers. The key is summing all digits and checking if the result is odd or even.
Advertisements
