給定數字的b+樹創建_在C ++中找到給定數字中的兩個的下一個和上一個冪

給定數字的b+樹創建

Problem statement:

問題陳述:

Find Next and previous power of two of a given number

查找給定數字中兩個的下一個和上一個冪

Next power of two

下一個二的冪

    Example(1):
input:  22
output: 32  ( as 32 is 2^5)
Example(2):
input: 54
output: 64  (as 64 is 2^6)

Previous power of two

以前的二的冪

    Example(1):
input:  22
output: 16
Example(2):
input:  54
output: 32

We can solve this problem using bit manipulation easily.

我們可以使用位操作輕松解決此問題。

Just have a look on the binary representation of the number which is a power of 2.

只需看一下數字的二進制表示形式就是2的冪。

    power of 2           Binary Representation
1                        1
2                        10
4                        100
8                        1000
16                       10000
32                       100000
64                       1000000
128                      10000000

As we can see every number have only their left most bit set (i.e 1) and rest are unset (i.e 0).

我們可以看到,每個數字只有最左邊的位(即1)被置位,其余的都未置位(即0)。

求2的前次冪 (Finding previous power of 2)

If we somehow, can unset all bits except the left most bit in a binary representation of number we will get previous power of two of the given number.

如果我們以某種方式可以取消設置二進制數字表示形式中除最左邊的位以外的所有位,我們將獲得給定數字的2的冪。

Example:

例:

    Number           Binary representation          previous power of two
7                  111                             100    (i,e 4)
25                11001                           10000   (i.e 16)
95               1011111                         1000000 (i,e 64)

We will use Bitwise AND ( & ) operation to clear bits.

我們將使用按位與(&)操作清除位。

Here is Algorithm to get previous power of 2 of n,

這是獲取n的2的先前冪的算法,

step 1: n = n & n-1
step 2: if n is power of two , n is our desired result,go to step 3.
else go to step 1.
step 3: print n and stop

Explanation:

說明:

let n   = 27 ( 11011 in binary)
n-1  = 26 ( 11010 in binary)
n&n-1 = 26
as 26 is not a power of 2 so we will repeat above step again
new n = 26
n   = 26  ( 11010 in binary)
n-1   = 25  ( 11001 in binary)
n&n-1 = 24  ( 11000 in binary)
as 24 is not a power of 2 so we will repeat above step again
new n=24
n   = 24  ( 11000 in binary)
n-1   = 23  ( 10111 in binary)
n&n-1 = 16  ( 10000 in binary)
as 16 is  a power of 2 so this is our answer

尋找二的下冪 (Finding next power of Two)

To get next power of two, all we have to do is to find a binary number greater than the given number having only left most bit set.

要獲得2的下一個冪,我們要做的就是找到一個比給定數字大的二進制數,該二進制數只剩下最左邊的位。

We can use left shift operator ( << )to generate a number having only its left most bit set.

我們可以使用左移運算符(<<)來生成僅設置其最左位的數字。

Left shift operation example:

左移操作示例:

1 << 5
This means that shift  1  left by 5 place
1 in binary is represented as  1
so after shifting 1 by 5 place left, 
output will be 100000 ( i.e 32 in decimal)
5 << 2
This means that shift  5  left by 2 place
5 in binary is represented as  101
so after shifting it by 2 place to left,
output will be 10100 ( i.e 20 in decimal)

Note: In each shift right most bit will be set to 0;

注意:在每個移位右移的大多數位將被設置為0;

Program:



程序:

</ s> </ s> </ s>
#include<bits/stdc++.h>
using namespace std;
long int  nextPowerOfTwo ( int  n )
{
// Result is intialized as 1
long int value = 1;
// The following while loop will run until we 
// get a number greater than n
while(value<=n)
{
// value will be left shifted by 1 place in each iteration
value=value << 1;
}
return value ;
}
int  previousPowerOfTwo(int  n )
{
// If n is already a power of two, we can simply shift it right 
// by 1 place and get the previous power of 2
// (n&n-1) will be 0 if n is power of two ( for n > = 2 )
// (n&&!(n&(n-1))) condition will take care of n < 2;
if((n&&!(n&(n-1)))==1)
{
return (n>>1);
}
// This while loop will run until we get a number which is a power of 2
while(n&n-1)
{
// Each time we are performing Bit wise And ( & )operation to clear bits
n=n&n-1;
}
return  n ;
}
int main()
{
int n;
cout << "Enter Number\n";
cin >> n;
long int num=nextPowerOfTwo(n);
cout << "Next power of two : " << num ;
cout << "\n\nEnter Number\n";
cin >> n;
num=previousPowerOfTwo(n);
cout << "Previous power of two : " << num ;
return 0;
}

Output

輸出量

    Enter Number
34
Next power of two : 64
Enter Number
34
Previous power of two : 32
Process returned 0 (0x0)   execution time : 7.681 s
Press any key to continue.

翻譯自: https://www.includehelp.com/cpp-programs/find-next-and-previous-power-of-two-of-a-given-number.aspx

給定數字的b+樹創建

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542668.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542668.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542668.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java 字節數組作用_這段java代碼中字節數組b起到了什么作用?

importjava.io.*;importjavax.swing.*;publicclassIOMonitor{publicstaticvoidmain(String[]temp){//TODO自動生成的方法存根byteb[]newbyte[2];try{FileInputStreamfisnewFileInput...import java.io.*;import javax.swing.*;public class IOMonitor {public static void main…

如何查看本地的崩潰log_過年回家,還怕搶不到票?程序員教你如何搶票

2019年接近尾聲&#xff0c;距離春節回家的日子越來越近&#xff0c;26日起&#xff0c;2020年除夕火車票正式開售&#xff0c;搶票大戰也進入白熱化階段。是否為某搶票 App 加速而煩惱&#xff0c;是否為車票“秒光而煩惱”。別慌&#xff0c;作為連“對象”都是 new 出來的程…

獲取列表中包含的元素數 在C#中

Given a list, and we have to count its total number of elements using List.Count property. 給定一個列表&#xff0c;我們必須使用List.Count屬性計算其元素總數 。 C&#xff03;清單 (C# List) A list is used to represent the list of the objects, it is represent…

I00037 虧數(Deficient number)

數論中&#xff0c;若一個正整數除了本身之外所有因子之和比此數自身小&#xff0c;則稱此數為虧數。虧數&#xff08;Deficient number&#xff09;也稱為缺數&#xff0c;參見百度百科_虧數&#xff0c;或參見維基百科的Deficient number。虧數在OEIS中的數列號為A005100。 問…

hashmap轉紅黑樹的閾值為8_面試必考的 HashMap,這篇總結到位了

點擊藍色“JavaKeeper”關注我喲加個“星標”&#xff0c;一起成長&#xff0c;做牛逼閃閃的技術人1 概述HashMap是基于哈希表實現的,每一個元素是一個key-value對,其內部通過單鏈表解決沖突問題,容量不足(超過了閥值)時,同樣會自動增長.HashMap是非線程安全的,只適用于單線程環…

linux用戶組管理命令_Linux用戶和組命令能力問題和解答

linux用戶組管理命令This section contains Aptitude Questions and Answers on Linux User and Group Commands. 本節包含有關Linux用戶和組命令的 Aptitude問答。 1) Which of the following commands is used to create a new user in the Linux operating system? create…

Failed to start firewalld.service: Unit firewalld.service is masked.

2019獨角獸企業重金招聘Python工程師標準>>> FireWall in Centos 7 masked How to resolve the error message belowFailed to issue method call: Unit firewalld.service is masked. The main reason a service is masked is to prevent accidental starting or e…

mysql第二個索引_MySQL高級第二章——索引優化分析

一、SQL性能下降原因1.等待時間長&#xff1f;執行時間長&#xff1f;可能原因&#xff1a;查詢語句寫的不行索引失效(單值索引、復合索引)CREATE INDEX index_user_name ON user(name);(底層做了一個排序)CREATE INDEX index_user_nameEmail ON user(name,email);查詢關聯join…

遞歸反轉鏈表改變原鏈表嗎_在不使用遞歸的情況下找到鏈表的長度

遞歸反轉鏈表改變原鏈表嗎Solution: 解&#xff1a; Algorithm to find length 查找長度的算法 Input: 輸入&#xff1a; A singly linked list whose address of the first node is stored in a pointer, say head. 一個單鏈表 &#xff0c;其第一個節點的地址存儲在指針(例…

西瓜仿站高手v1.08官方正式版

2019獨角獸企業重金招聘Python工程師標準>>> 西瓜仿站高手是一款綠色好用的由追風網絡出品的網站模板批量下載軟件&#xff0c;西瓜仿站高手是一款仿站工具&#xff0c;仿站神器。軟件功能強大&#xff0c;能夠幫你輕松幫你下載任意網站、任意模板&#xff0c;并且速…

用hundred造句子_八個有趣的開學破冰游戲,線上線下都能用

知道大家最近都很忙&#xff0c;所以省略開篇&#xff0c;直接上正題——開學“破冰游戲”走起&#xff01;一、你比劃我來猜把詞語展示在PPT上&#xff0c;猜詞的同學背對PPT&#xff0c;其他同學可以看到詞語并且用身體動作把詞語表現出來&#xff0c;直到猜詞的同學可以把詞…

java 執行順序_Java代碼執行順序

程序中代碼執行的順序非常重要&#xff0c;稍有不慎便會是程序運行出錯&#xff0c;那么我將結合實例來分析代碼中的執行。名詞解釋首先了解幾個名詞&#xff1a;非靜態代碼塊直接由 { } 包起來的代碼&#xff0c;稱為非靜態代碼塊靜態代碼塊直接由 static { } 包起來的代碼&am…

mysql 包含的那些文件

*.frm是描述了表的結構 *.MYD保存了表的數據記錄 *.MYI則是表的索引 ibd是MySQL數據文件、索引文件&#xff0c;無法直接讀取。 轉載于:https://www.cnblogs.com/07byte/p/5823667.html

math 計算float_Java Math類靜態float min(float f1,float f2)與示例

math 計算float數學類靜態浮點數min(float f1&#xff0c;float f2) (Math Class static float min(float f1 , float f2) ) This method is available in java.lang package. 此方法在java.lang包中可用。 This method is used to return the minimum one of both the given a…

vector 不初始化時什么狀態_Vue原理解析(三):初始化時created之前做了什么?...

讓我們繼續this._init()的初始化之旅&#xff0c;接下來又會執行這樣的三個初始化方法&#xff1a;initInjections(vm) initState(vm) initProvide(vm)5. initInjections(vm): 主要作用是初始化inject&#xff0c;可以訪問到對應的依賴。inject和provide這里需要簡單的提一下&a…

switch 字符串 java_JDK7新特性switch支持字符串

在JDK7中,switch語句的判斷條件增加了對字符串類型的支持。由于字符串的操作在編程中使用頻繁,這個新特性的出現為Java編程帶來了便利。接下來通過一個案例演示一下在switch語句中使用字符串進行匹配。public class Example {public static void main(String[] args) {String w…

cisco packet tracer路由器配置_【干貨】思科交換機路由器怎么配置密碼?

今天帶大家看看如何在思科的交換機路由器當中配置安全特性&#xff0c;也就是密碼的配置方式。在學習配置之前&#xff0c;我們先回顧一下密碼相關知識。密碼學是研究信息系統安全保密的科學。人類有記載的通信密碼始于公元前400年&#xff0c;古希臘人是置換密碼學的發明者。密…

perl 哈希數組的哈希_使用哈希檢查兩個數組是否相似

perl 哈希數組的哈希Prerequisite: Hashing data structure 先決條件&#xff1a; 哈希數據結構 Problem statement: 問題陳述&#xff1a; Check whether two arrays are similar or not using the hash table. The arrays are of the same size. 使用哈希表檢查兩個數組是否…

codevs3872 郵遞員送信(SPFA)

郵遞員送信 時間限制: 1 Sec 內存限制: 64 MB提交: 10 解決: 5[提交][狀態][討論版] 題目描述 有一個郵遞員要送東西&#xff0c;郵局在節點1.他總共要送N-1樣東西&#xff0c;其目的地分別是2~N。由于這個城市的交通比較繁忙&#xff0c;因此所有的道路都是單行的&#xff0…

java上傳csv文件上傳_java處理csv文件上傳示例詳解

前言&#xff1a;示例只是做了一個最最基礎的上傳csv的示例&#xff0c;如果要引用到代碼中去&#xff0c;還需要根據自己的業務自行添加一些邏輯處理。readcsvutil工具類package com.hanfengyeqiao.gjb.utils;import java.io.*;import java.util.*;/*** csv工具類*/public cla…