Skip to content

08. Bitwise Operators #8

@xgqfrms

Description

@xgqfrms

Bitwise Operators

位操作

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators

demo

Advanced-Frontend/Daily-Interview-Question#161 (comment)

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2019-08-14
 *
 * @description auto-sevent-times-without-math.js
 * @description 不用加减乘除运算符, 求整数的7倍
 * @description js array get sum value without call math methods
 * @augments
 * @example eval([1,2,3].join('+'));// 6
 * @link https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers
 *
 */

let log = console.log;

const autoSevenTimes = (int = 0, times = 7, debug = false) => {
    let result = [];
    if (!int) {
        return 0;
    } else {
        for (let i = 0; i < times; i++) {
            result.push(int);
        }
    }
    // result = result.reduce((acc, item) => acc + item);
    result = eval(result.join(`+`));
    if(debug) {
        log(`result = `, result);
    }
    return result;
};

let num = 3;
autoSevenTimes(num);
// expect: 3 * 7 = 21

bitwise-operator

https://repl.it/@xgqfrms/bitwise-operator-and-left-shift-and-right-shift

const autoSeventTimes = (num = 0, times = 7) => {
    let x = Math.floor(times / 2);
    // 左移 n 位操作,倍增 2^n 倍
    // 左移 3 位,扩大8 倍(2 ** 3);倍增后,减去一次自身, 等于 7 倍
    return (num << x) - num;
};

let xyz = autoSeventTimes(3);
// 21

console.log(`xyz =`, xyz);
// 3 === 00000011
// 24 === 00011000

// 21 === 00010101


// 0b 二进制
// 0o 十六进制
let x = 0b00010101;
// 21

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#binary_numbers

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions