Saturday, August 6, 2016

Adding without using + operator

function addWithoutPlusOperator (a, b){ // 111, 111
    var sumWithoutCarry = a ^ b; // 000
    var carryWithoutSum =  (a & b) << 1;  //111 << 1 = 1110
    return addWithoutPlusOperator( sumWithoutCarry, carryWithoutSum );
}

Swapping without using extra variable

function swap (a, b){ // 5,7
    a = b - a; // 7-5 = 2
    b = b - a; // 7-2 = 5
    a = a + b; // 2 + 5 = 7
}

Private, Public variables using Javascript closures

Tuesday, August 2, 2016

Find Duplicate Element

Given: a list of integers where, the integers in the list are in the range 1..n and the list has a length of n+1. Find the duplicate element. The complexity of should be at most O(n).

Link to Code on JSfiddle: https://jsfiddle.net/dhiviyad/zwsan7zt/1/