Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit51a9126

Browse files
committed
Added SetBit.js, SetBit.test.js in Bit-Manipulation directory
1 parent709de83 commit51a9126

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

‎Bit-Manipulation/SetBit.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Setting Bit: https://www.geeksforgeeks.org/set-k-th-bit-given-number/
3+
*
4+
* To set any bit we use bitwise OR (|) operator.
5+
*
6+
* Bitwise OR (|) compares the bits of the 32
7+
* bit binary representations of the number and
8+
* returns a number after comparing each bit.
9+
*
10+
* 0 | 0 -> 0
11+
* 0 | 1 -> 1
12+
* 1 | 0 -> 1
13+
* 1 | 1 -> 1
14+
*
15+
* In-order to set kth bit of a number (where k is the position where bit is to be changed)
16+
* we need to shift 1 k times to its left and then perform bitwise OR operation with the
17+
* number and result of left shift performed just before.
18+
*
19+
* References:
20+
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR
21+
*/
22+
23+
/**
24+
*@param {number} number
25+
*@param {number} bitPosition - zero based.
26+
*@return {number}
27+
*/
28+
29+
exportconstsetBit=(number,bitPosition)=>{
30+
returnnumber|(1<<bitPosition)
31+
}

‎Bit-Manipulation/test/SetBit.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import{setBit}from'../SetBit'
2+
3+
test('should set bit at the given bit Position',()=>{
4+
constsetBitPos=setBit(1,0)
5+
expect(setBitPos).toBe(1)
6+
})
7+
8+
test('should set bit at the given bit Position',()=>{
9+
constsetBitPos=setBit(1,0)
10+
expect(setBitPos).toBe(1)
11+
})
12+
13+
test('should set bit at the given bit Position',()=>{
14+
constsetBitPos=setBit(10,1)
15+
expect(setBitPos).toBe(10)
16+
})
17+
18+
test('should set bit at the given bit Position',()=>{
19+
constsetBitPos=setBit(10,2)
20+
expect(setBitPos).toBe(14)
21+
})

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp