From 164eec6e5ca6d41e6d67e8923c8ab54bf9a3e20e Mon Sep 17 00:00:00 2001 From: Kamilla Date: Sat, 2 Jul 2016 19:38:55 -0400 Subject: [PATCH 1/3] problem 17.1 --- Chapter17-Moderate/swapNumbers.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Chapter17-Moderate/swapNumbers.js 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 From b7d3bfc7a74e5fe0a07cc29af0d90ce2e36da1ad Mon Sep 17 00:00:00 2001 From: Kamilla Date: Sat, 2 Jul 2016 20:19:03 -0400 Subject: [PATCH 2/3] problem 18.1 --- Chapter18-Hard/18.1-addition.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Chapter18-Hard/18.1-addition.js 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 From 61ee1fc19c0a15a56e92999c4e0890ba57fda0ae Mon Sep 17 00:00:00 2001 From: KamillaKhabibrakhmanova Date: Sat, 6 Aug 2016 00:05:13 -0400 Subject: [PATCH 3/3] solution to 17.3 --- Chapter17-Moderate/17.3-trailingZeroes.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Chapter17-Moderate/17.3-trailingZeroes.js 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