[leetcode] 64. Conditional sum, recursion + Shift

Time:2021-6-15

To find 1 + 2 +… + N, it is required that keywords such as multiplication and division, for, while, if, else, switch, case, and conditional judgment statements (a? B: C) cannot be used.

Example 1:
Input: n = 3
Output: 6
Example 2:
Input: n = 9
Output: 45

Restrictions:
1 <= n <= 10000

How to solve the problem:

  • 1. Recursion
  • 2. Shift operator

1. Recursion

/**
 * @param {number} n
 * @return {number}
 */
var sumNums = function(n) {
    let sum = n;
    return n > 0 && (sum += sumNums(n - 1))
};

2. Shift operator

Solution code:

/**
 * @param {number} n
 * @return {number}
 */
var sumNums = function(n) {
    return (Math.pow(n, 2) + n) >> 1
};

JS shift operator supplement:

1. “<” operator

The “<” operator performs a left shift operation. In the process of shift operation, the symbol bit remains unchanged. If the right side is empty, it will be automatically filled with 0; If the value exceeds 32 bits, it will be discarded automatically.

Move the number 5 2 bits to the left, and the return value is 20.

2. “>” operator

The “> >” operator performs a signed shift right operation. In contrast to the shift left operation, it shifts all significant bits of a 32-bit number to the right, and then fills the empty bits with the value of the sign bit. Values exceeded during the move will be discarded.

Move the value 1000 8 bits to the right, and the return value is 3.

3. “>” operator

The “>” operator performs a five symbol right shift operation. It shifts all the bits of an unsigned 32-bit integer to the right. For the right shift operation of an unsigned number or a positive number, the result of the right shift operation of an unsigned number is the same as that of a signed number.

The return values of the following two lines are the same.

console.log(1000 >>> 8);  // Return value 3
    console.log(1000 >> 8);  // Return value 3