loading...

re: Daily Challenge #257 - Halving Sum VIEW POST

FULL DISCUSSION
 

Looping

const halvingSum = (n: number): number => {
  let sum = 0;

  while (n !== 0) {
    sum += n;
    n = Math.floor(n / 2);
  }

  return sum;
}

Recursion

const halvingSum = (n: number): number => {
  if (n === 0) {
    return n;
  }

  return n + halvingSum(Math.floor(n / 2))
}

Tail Recursion

const halvingSum = (n: number, sum: number = 0): number => {
  if (n === 0) {
    return sum;
  }

  return halvingSum(Math.floor(n / 2), sum + n);
}
Code of Conduct Report abuse