Fancy DSA Fancy DSA
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)

Jonsam NG

想的更多,也要想的更远
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)
  • 开始上手
  • Plan 计划
  • Roadmap 路线
  • 算法简介
  • Sort 排序

  • Search 搜索

  • Recursive 递归

  • Graph 图

  • Tree 树

  • Math 数学

  • Hash 哈希

  • String 字符串

  • BitManipulation 位操纵

    • BinaryCountSetBits [二进制串数1]
    • PowerOfTwo [2的幂]
      • 介绍
      • 实现
      • 扩展
    • SetBit [位操作]
  • Backtracking 回溯

  • DynamicProgramming 动态规划

  • Cache 缓存

  • Array 数组

  • Ciphers 密码学

  • Conversions 转换

  • ProjectEuler 欧拉计划

  • 其他

  • 算法
  • BitManipulation 位操纵
jonsam
2022-05-01
目录

PowerOfTwo [2的幂]

# 介绍

如果只有一个 bit 被设置,其余的都没有被设置,那么一个数字将是 2 的幂。如果 n 是 2 的幂,难么 n-1 将会对 n 的所有 bit 进行取反,即 n&(n-1) = 0 。

# 实现

# JavaScript

/*
    author: @Aayushi-Mittal

    This script will check whether the given
    number is a power of two or not.

    A number will be a power of two if only one bit is set and rest are unset.
    This is true for all the cases except 01 because (2^0 = 1) which is not a power of 2.
    For eg: 10 (2^1 = 2), 100 (2^2 = 4), 10000 (2^4 = 16)

    Reference Link: https://www.hackerearth.com/practice/notes/round-a-number-to-the-next-power-of-2/

    If we will subtract 1 from a number that is a power of 2 we will get it's 1's complement.
    And we know that 1's complement is just opp. of that number.
    So, (n & (n-1)) will be 0.

    For eg:    (1000 & (1000-1))
                1 0 0 0     // Original Number (8)
                0 1 1 1     // After Subtracting 1 (8-1 = 7)
                _______
                0 0 0 0     // will become 0

*/

export const IsPowerOfTwo = (n) => {
  if (n > 0 && (n & (n - 1)) === 0) {
    return true
  }
  return false
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 扩展

找到下一个大于 n 的 2 的幂。

/**
 *
 *  This script will find next power of two
 *    of given number.
 *  More about it:
 *   https://www.techiedelight.com/round-next-highest-power-2/
 *
 */
const nextPowerOfTwo = (n) => {
  if (n > 0 && (n & (n - 1)) === 0) return n
  let result = 1
  while (n > 0) {
    result = result << 1
    n = n >> 1
  }
  return result
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
编辑 (opens new window)
上次更新: 2022/10/20, 21:51:45
BinaryCountSetBits [二进制串数1]
SetBit [位操作]

← BinaryCountSetBits [二进制串数1] SetBit [位操作]→

最近更新
01
0-20题解
10-31
02
本章导读
10-31
03
算法与转换:Part1
10-28
更多文章>
Theme by Vdoing | Copyright © 2022-2022 Fancy DSA | Made by Jonsam by ❤
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式