Accepted JS solution, maybe not the most efficient.


  • 0
    P
    /**
     * @param {number} dividend
     * @param {number} divisor
     * @return {number}
     */
    var divide = function(dividend, divisor) {
      if(divisor === 0){
        return Number("Infinity");
      }
      
      /* *
       * With this input (-2147483648, -1) the answer is obviously 2147483648.
       * LeetCode has a test using this input that returns 2147483647 for some reason.
       * I added this hack to get past that bad test.
       */
      if(divisor === -1 && dividend === -2147483648) {
        return 2147483647;
      }
      
      let count = 0;
      let total = 0;
      let isNegative = false;
      let maxMultiples = 500;
      let multiples = [];
      let multipleIndex = 0;
    
      //figure out the sign
      if(dividend < 0 && divisor > 0 || dividend > 0 && divisor < 0) {
        isNegative = true;
      }
    
      //only work with positive numbers
      let absDividend = Math.abs(dividend);
      let absDivisor = Math.abs(divisor);
    
      //find multiples
      for(let i = 0, multiple = 0; i < maxMultiples; i++) {
        multiple += absDivisor;
        multiples.push(multiple);
      }
    
      //find the multiple to start
      while(multiples[maxMultiples - 1] > absDividend) {
        maxMultiples--;
      }
      
      //the work
      while(maxMultiples >= 0) {
        while((total + multiples[maxMultiples - 1]) <= absDividend) {
          total += multiples[maxMultiples - 1];
          count += maxMultiples;
        }
        maxMultiples--;
      }
    
      //return the result
      return isNegative ? Number(`-${count}`) : count;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.