Complete the code to get the digit at a specific place value.
function getDigit(num, place) {
return Math.floor(Math.abs(num) / [1]) % 10;
}The digit at a given place is found by dividing the number by 10 raised to that place, then taking the remainder when divided by 10.
Complete the code to count the number of digits in a number.
function digitCount(num) {
if (num === 0) return 1;
return Math.floor(Math.log10(Math.abs(num))) + [1];
}Adding 1 after floor of log base 10 gives the total digits count.
Fix the error in the code to find the maximum number of digits in an array.
function mostDigits(nums) {
let maxDigits = 0;
for (let i = 0; i < nums.length; i++) {
maxDigits = Math.max(maxDigits, [1](nums[i]));
}
return maxDigits;
}We use digitCount to find how many digits each number has and track the maximum.
Fill both blanks to correctly place numbers into buckets by digit and flatten the array.
for (let k = 0; k < maxDigitCount; k++) { let buckets = Array.from({ length: 10 }, () => []); for (let i = 0; i < nums.length; i++) { let digit = [1](nums[i], k); buckets[digit].[2](nums[i]); } nums = [].concat(...buckets); }
getDigit gets the digit at place k; push adds the number to the correct bucket.
Fill all three blanks to complete the radix sort function.
function radixSort(nums) {
let maxDigitCount = [1](nums);
for (let k = 0; k < maxDigitCount; k++) {
let buckets = Array.from({ length: 10 }, () => []);
for (let i = 0; i < nums.length; i++) {
let digit = [2](nums[i], k);
buckets[digit].push(nums[i]);
}
nums = [].concat(...buckets);
}
return nums;
}
// Helper functions
function digitCount(num) {
if (num === 0) return 1;
return Math.floor(Math.log10(Math.abs(num))) + 1;
}
function mostDigits(nums) {
let maxDigits = 0;
for (let i = 0; i < nums.length; i++) {
maxDigits = Math.max(maxDigits, digitCount(nums[i]));
}
return maxDigits;
}
function getDigit(num, place) {
return Math.floor(Math.abs(num) / (10 ** place)) % 10;
}mostDigits finds max digits in array, getDigit gets digit at place, digitCount counts digits.