javascript
exercises
exercises.js⚡javascript
/**
* =====================================================
* 4.4 WHILE AND DO-WHILE LOOPS - EXERCISES
* =====================================================
* Practice condition-based iteration
*/
/**
* Exercise 1: Count Digits
*
* Count the number of digits in a positive integer.
* Use a while loop.
*/
function countDigits(n) {
// TODO: Count how many digits are in n
// Hint: Keep dividing by 10 until n becomes 0
}
// Test cases:
console.log("Exercise 1:");
console.log(countDigits(12345)); // 5
console.log(countDigits(1)); // 1
console.log(countDigits(1000)); // 4
console.log(countDigits(0)); // 1
/**
* Exercise 2: Sum of Digits
*
* Calculate the sum of all digits in a number.
*/
function sumDigits(n) {
// TODO: Sum all digits of n
// Hint: Use modulo to get last digit, divide to remove it
}
// Test cases:
console.log("\nExercise 2:");
console.log(sumDigits(12345)); // 15 (1+2+3+4+5)
console.log(sumDigits(999)); // 27
console.log(sumDigits(100)); // 1
/**
* Exercise 3: Power of Two Check
*
* Check if a number is a power of 2.
* Use a while loop (don't use Math.log).
*/
function isPowerOfTwo(n) {
// TODO: Check if n is a power of 2
// Hint: Keep dividing by 2 while divisible
}
// Test cases:
console.log("\nExercise 3:");
console.log(isPowerOfTwo(1)); // true (2^0)
console.log(isPowerOfTwo(16)); // true (2^4)
console.log(isPowerOfTwo(64)); // true (2^6)
console.log(isPowerOfTwo(12)); // false
console.log(isPowerOfTwo(0)); // false
/**
* Exercise 4: Greatest Common Divisor (GCD)
*
* Find the GCD of two numbers using Euclidean algorithm.
*/
function gcd(a, b) {
// TODO: Implement Euclidean algorithm
// While b is not 0: a becomes b, b becomes a % b
// Return a when b is 0
}
// Test cases:
console.log("\nExercise 4:");
console.log(gcd(48, 18)); // 6
console.log(gcd(100, 25)); // 25
console.log(gcd(17, 13)); // 1 (coprime)
console.log(gcd(0, 5)); // 5
/**
* Exercise 5: Decimal to Binary
*
* Convert a decimal number to binary string.
*/
function decimalToBinary(n) {
// TODO: Convert n to binary representation
// Hint: Get remainder when dividing by 2, build string from right to left
}
// Test cases:
console.log("\nExercise 5:");
console.log(decimalToBinary(10)); // "1010"
console.log(decimalToBinary(42)); // "101010"
console.log(decimalToBinary(255)); // "11111111"
console.log(decimalToBinary(0)); // "0"
/**
* Exercise 6: Password Validator (Simulated)
*
* Simulate password validation that allows 3 attempts.
* Return true if any attempt matches, false after 3 failures.
*/
function simulatePasswordCheck(correctPassword, attempts) {
// attempts is an array of password guesses
// Use do-while to check each attempt (max 3)
// Return true if correct password found
}
// Test cases:
console.log("\nExercise 6:");
console.log(simulatePasswordCheck("secret", ["wrong", "secret"])); // true (2nd try)
console.log(simulatePasswordCheck("secret", ["a", "b", "c"])); // false
console.log(simulatePasswordCheck("secret", ["secret"])); // true (1st try)
/**
* Exercise 7: Collatz Sequence Length
*
* Count steps to reach 1 using Collatz conjecture:
* - If even: n = n / 2
* - If odd: n = 3n + 1
*/
function collatzLength(n) {
// TODO: Count steps until n becomes 1
}
// Test cases:
console.log("\nExercise 7:");
console.log(collatzLength(1)); // 0
console.log(collatzLength(2)); // 1
console.log(collatzLength(6)); // 8
console.log(collatzLength(27)); // 111
/**
* Exercise 8: Find First Multiple
*
* Find the first number >= start that is divisible by both a and b.
*/
function firstCommonMultiple(start, a, b) {
// TODO: Find first number >= start divisible by both a and b
}
// Test cases:
console.log("\nExercise 8:");
console.log(firstCommonMultiple(1, 3, 5)); // 15
console.log(firstCommonMultiple(10, 4, 6)); // 12
console.log(firstCommonMultiple(100, 7, 11)); // 154
/**
* Exercise 9: Reverse String (using while)
*
* Reverse a string using a while loop.
*/
function reverseString(str) {
// TODO: Reverse the string using while loop
}
// Test cases:
console.log("\nExercise 9:");
console.log(reverseString("hello")); // "olleh"
console.log(reverseString("JavaScript")); // "tpircSavaJ"
console.log(reverseString("a")); // "a"
console.log(reverseString("")); // ""
/**
* Exercise 10: Repeated Squaring
*
* Calculate base^exponent using repeated squaring (efficient method).
* This is O(log n) instead of O(n).
*/
function power(base, exponent) {
// TODO: Implement using repeated squaring
// While exponent > 0:
// If exponent is odd: multiply result by base
// Square base, halve exponent
}
// Test cases:
console.log("\nExercise 10:");
console.log(power(2, 10)); // 1024
console.log(power(3, 5)); // 243
console.log(power(5, 0)); // 1
console.log(power(7, 2)); // 49
// =====================================================
// BONUS CHALLENGES
// =====================================================
/**
* Bonus 1: Guess the Number Game
*
* Simulate a number guessing game.
* Return the number of guesses it took.
*
* guesses: array of guesses made
* secret: the number to guess
*/
function playGuessingGame(guesses, secret) {
// TODO: Process guesses, return attempt count when correct
// If never correct, return -1
}
console.log("\nBonus 1:");
console.log(playGuessingGame([50, 75, 63, 70], 70)); // 4
console.log(playGuessingGame([1, 2, 3], 5)); // -1
/**
* Bonus 2: Newton's Square Root
*
* Calculate square root using Newton's method:
* guess = (guess + n/guess) / 2
* Repeat until abs(guess² - n) < 0.0001
*/
function squareRoot(n) {
// TODO: Implement Newton's method for square root
}
console.log("\nBonus 2:");
console.log(squareRoot(16)); // ~4
console.log(squareRoot(2)); // ~1.414
console.log(squareRoot(100)); // ~10
/**
* Bonus 3: Digital Root
*
* Keep summing digits until you get a single digit.
* Example: 9875 → 29 → 11 → 2
*/
function digitalRoot(n) {
// TODO: Keep summing digits until single digit
}
console.log("\nBonus 3:");
console.log(digitalRoot(9875)); // 2
console.log(digitalRoot(123456)); // 3
console.log(digitalRoot(5)); // 5
// =====================================================
// SOLUTIONS (Uncomment to check your answers)
// =====================================================
/*
// Exercise 1 Solution:
function countDigits(n) {
if (n === 0) return 1;
let count = 0;
n = Math.abs(n);
while (n > 0) {
count++;
n = Math.floor(n / 10);
}
return count;
}
// Exercise 2 Solution:
function sumDigits(n) {
let sum = 0;
n = Math.abs(n);
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
}
// Exercise 3 Solution:
function isPowerOfTwo(n) {
if (n < 1) return false;
while (n > 1) {
if (n % 2 !== 0) return false;
n = n / 2;
}
return true;
}
// Exercise 4 Solution:
function gcd(a, b) {
a = Math.abs(a);
b = Math.abs(b);
while (b !== 0) {
const temp = b;
b = a % b;
a = temp;
}
return a;
}
// Exercise 5 Solution:
function decimalToBinary(n) {
if (n === 0) return "0";
let binary = "";
while (n > 0) {
binary = (n % 2) + binary;
n = Math.floor(n / 2);
}
return binary;
}
// Exercise 6 Solution:
function simulatePasswordCheck(correctPassword, attempts) {
let i = 0;
do {
if (attempts[i] === correctPassword) {
return true;
}
i++;
} while (i < 3 && i < attempts.length);
return false;
}
// Exercise 7 Solution:
function collatzLength(n) {
let steps = 0;
while (n !== 1) {
if (n % 2 === 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
steps++;
}
return steps;
}
// Exercise 8 Solution:
function firstCommonMultiple(start, a, b) {
let n = start;
while (n % a !== 0 || n % b !== 0) {
n++;
}
return n;
}
// Exercise 9 Solution:
function reverseString(str) {
let reversed = "";
let i = str.length - 1;
while (i >= 0) {
reversed += str[i];
i--;
}
return reversed;
}
// Exercise 10 Solution:
function power(base, exponent) {
let result = 1;
while (exponent > 0) {
if (exponent % 2 === 1) {
result *= base;
}
base *= base;
exponent = Math.floor(exponent / 2);
}
return result;
}
// Bonus 1 Solution:
function playGuessingGame(guesses, secret) {
let i = 0;
while (i < guesses.length) {
if (guesses[i] === secret) {
return i + 1;
}
i++;
}
return -1;
}
// Bonus 2 Solution:
function squareRoot(n) {
let guess = n / 2;
while (Math.abs(guess * guess - n) >= 0.0001) {
guess = (guess + n / guess) / 2;
}
return Math.round(guess * 10000) / 10000;
}
// Bonus 3 Solution:
function digitalRoot(n) {
while (n >= 10) {
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
n = sum;
}
return n;
}
*/