Skip to content
Open

17.3 #16

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Chapter17-Moderate/17.3-trailingZeroes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
Problem: Write an algorithm which computes the number of trailing zeroes in n factorial.
*/

function factorial(n) {
if (n ===1 ) return 1;
return n * factorial(n-1);
}

function trailingZeroes(n) {
var count = Math.floor(n/5);
for (var i = 25; n/i >= 1; i *= 5) {
count += Math.floor(n/i);
}
return count;
}
15 changes: 15 additions & 0 deletions Chapter17-Moderate/swapNumbers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
Write a function to swap a number in place (that is, without any temporary variables).
*/

function switchVals(a,b) {
if (a > b) {
a = a - b;
b = a + b;
a = b - a;
} else if (b > a) {
b = b - a;
a = a + b;
b = a - b;
}
}
18 changes: 18 additions & 0 deletions Chapter18-Hard/18.1-addition.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
Write a function that adds two numbers. You should not use + or any arithmetic operators.
*/

//convert numbers to binary in order to perform operations on them
function add(num1, num2) {
let bin1 = num1.toString(2);
let bin2 = num2.toString(2);
return parseInt(addBinary(bin1, bin2), 2);
}

//recursively add binary numbers using XOR and AND
function addBinary(bin1, bin2) {
if (bin2 === 0) return bin1;
let sum = bin1 ^ bin2;
let carry = (bin1 & bin2) << 1;
return addBinary(sum, carry);
}