diff --git a/Chapter17-Moderate/17.3-trailingZeroes.js b/Chapter17-Moderate/17.3-trailingZeroes.js new file mode 100644 index 0000000..920ddb0 --- /dev/null +++ b/Chapter17-Moderate/17.3-trailingZeroes.js @@ -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; +} \ No newline at end of file diff --git a/Chapter17-Moderate/swapNumbers.js b/Chapter17-Moderate/swapNumbers.js new file mode 100644 index 0000000..e5b9235 --- /dev/null +++ b/Chapter17-Moderate/swapNumbers.js @@ -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; + } +} \ No newline at end of file diff --git a/Chapter18-Hard/18.1-addition.js b/Chapter18-Hard/18.1-addition.js new file mode 100644 index 0000000..157b0cf --- /dev/null +++ b/Chapter18-Hard/18.1-addition.js @@ -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); +} \ No newline at end of file