Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checking if a number is a valid power of 4 in JavaScript
Problem
We are required to write a JavaScript function that takes in a single integer, num, as the only argument. Our function should check whether this number is a valid power of 4 or not. If it is a power of 4, we should return true, false otherwise.
For example, if the input to the function is −
const num1 = 2356; const num2 = 16;
Then the output should be −
const output1 = false; const output2 = true;
Example
The code for this will be −
const num1 = 2356;
const num2 = 16;
const isPowerOfFour = (num = 1) => {
let bool = false;
for(let i = 0; i < 16; i++){
if( Math.pow(4,i) === num){
bool=true;
return bool;
};
};
return bool;
};
console.log(isPowerOfFour(num1));
console.log(isPowerOfFour(num2));
Output
And the output in the console will be −
false true
Advertisements