Bit Magic
Bit Magic
1
Contents
15 Bit Fields in C 90
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
29 CHAR_BIT in C 172
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
2
Contents
45 Check if a number has bits in alternate pattern | Set-2 O(1) Approach 270
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
46 Check if a number has same number of set and unset bits 275
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
3
Contents
4
Contents
68 Check if two numbers are bit rotations of each other or not 412
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
69 Check if two numbers are equal without using arithmetic and compari-
son operators 416
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
70 Check if two numbers are equal without using comparison operators 420
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
74 Check whether all the bits are set in the given range 446
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
75 Check whether all the bits are unset in the given range 452
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
76 Check whether all the bits are unset in the given range or not 458
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
77 Check whether bits are in alternate pattern in the given range 463
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
78 Check whether bits are in alternate pattern in the given range | Set-2 471
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
80 Check whether the number has only first and last bits set 480
5
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
81 Check whether the number has only first and last bits set | Set 2 485
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
82 Check whether the two numbers differ at one bit position only 490
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
83 Closest (or Next) smaller and greater numbers with same number of
set bits 494
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
88 Compute the parity of a number using XOR and table look-up 534
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
6
Contents
97 Count minimum bits to flip such that XOR of A and B equal to C 574
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
101 Count numbers whose sum with x is equal to XOR with x 593
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
102 Count of divisors having more set bits than quotient on dividing N 601
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
103 Count pairs in an array which have at least one digit common 611
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
112 Count smaller numbers whose XOR with n produces greater value 680
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
113 Count smaller values whose XOR with x is greater than x 687
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
7
Contents
128 Divide two integers without using multiplication, division and mod
operator 799
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
8
Contents
132 Efficiently check if a string has duplicates without using any additional
data structure 825
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830
134 Efficiently find first repeated character in a string without using any
additional data structure in one traversal 835
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839
145 Find Two Missing Numbers | Set 2 (XOR based solution) 883
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892
147 Find XOR of two number without using XOR operator 900
9
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 904
149 Find i’th index character in a binary string obtained after n iterations
| Set 2 909
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
150 Find largest element from array without using conditional operator 918
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 921
151 Find longest sequence of 1’s in binary representation with one flip 922
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
152 Find missing number in another array which is shuffled copy 928
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 933
155 Find number of pairs in an array such that their XOR is 0 953
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962
159 Find smallest number n such that n XOR n+1 equals to given k. 990
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 994
162 Find the largest number with n set and m unset bits 1020
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1025
10
Contents
166 Find the n-th number whose binary representation is a palindrome 1053
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1063
167 Find the smallest number with n set and m unset bits 1064
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1069
170 Find two numbers from their sum and XOR 1079
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1084
175 For every set bit of a number toggle bits of other 1108
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1111
11
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1136
181 Given a set, find XOR of the XOR’s of all subsets. 1137
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1141
185 How to swap two numbers without using a temporary variable? 1163
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1174
190 Inserting M into N such that m starts at bit j and ends at bit i | Set-21200
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1208
191 Inserting m into n such that m starts at bit j and ends at bit i. 1209
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1215
195 Largest number with binary representation is m 1’s and m-1 0’s 1235
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1241
12
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1246
202 Lucky alive person in a circle | Code Solution to sword puzzle 1281
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1283
207 Maximum 0’s between two immediate 1’s in binary representation 1308
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1312
213 Maximum set bit sum in array without considering adjacent elements 1344
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1350
13
Contents
216 Maximum sum by adding numbers with same number of set bits 1364
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1370
217 Minimum bit changes in Binary Circular array to reach a index 1371
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1374
220 Minimum flips required to maximize a number with k set bits 1388
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1394
221 Minimum flips to make all 1s in left and 0s in right | Set 1 (Using
Bitmask) 1395
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1397
14
Contents
232 Next greater integer having one more number of set bits 1448
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1453
233 Next higher number with same number of set bits 1454
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1458
238 Number whose XOR sum with given array is a given number k 1484
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1488
239 Number whose sum of XOR with given array range is maximum 1489
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1499
240 Number with set bits only between L-th and R-th index 1500
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1507
241 Numbers whose bitwise OR and sum with N are equal 1508
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1514
15
Contents
249 Position of rightmost bit with first carry in sum of two binary 1550
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1553
255 Previous smaller integer having one less number of set bits 1585
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1589
258 Print all the combinations of N elements by changing sign such that
their sum is divisible by M 1599
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1606
260 Print first n numbers with exactly two set bits 1614
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1619
261 Print numbers having first and last bits as the only set bits 1620
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1630
262 Print numbers in the range 1 to n having bits in alternate pattern 1631
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1638
16
Contents
269 Python Slicing | Extract ‘k’ bits from a given position 1675
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1676
270 Python map function | Count total set bits in all numbers from 1 to n1677
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1678
274 Queries for number of array elements in a range with Kth Bit Set 1686
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1693
280 Reverse an array without using subtract sign ‘-‘ anywhere in the code1724
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1726
17
Contents
283 Russian Peasant (Multiply two numbers using bitwise operators) 1735
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1740
293 Smallest number whose set bits are maximum in a given range 1801
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1808
18
Contents
308 Sum of bitwise AND of all possible subsets of given set 1914
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1921
312 Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n 1945
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1952
19
Contents
321 Toggle all the bits of a number except k-th bit. 1999
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2000
323 Toggle bits of a number except first and last bits 2006
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2011
328 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) 2031
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2032
330 Two odd occurring elements in an array where all other occur even
times 2037
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2042
331 Unique element in an array where all elements occur k times except one 2043
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2045
20
Contents
337 Ways to split array into two groups of same XOR value 2071
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2075
338 What are the differences between bitwise and logical AND operators
in C/C++? 2076
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2078
339 Write a function that returns 2 for input 1 and returns 1 for 2 2079
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2080
348 XOR of two numbers after making length of their binary representa-
tions equal 2127
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2134
21
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2139
22
Chapter 1
Input : n = 4
Output : 1 2 4 5 8 9 10
These are numbers with 1 to 4
bits and no consecutive ones in
binary representation.
Input : n = 3
Output : 1 2 4 5
C++
23
Chapter 1. 1 to n bit numbers with no consecutive 1s in binary representation
#include<iostream>
using namespace std;
void printNonConsecutive(int n)
{
// Let us first compute
// 2 raised to power n.
int p = (1 << n);
// loop 1 to n to check
// all the numbers
for (int i = 1; i < p; i++)
// A number i doesn't contain
// consecutive set bits if
// bitwise and of i and left
// shifted i do't contain a
// commons set bit.
if ((i & (i << 1)) == 0)
cout << i << " ";
}
// Driver code
int main()
{
int n = 3;
printNonConsecutive(n);
return 0;
}
Java
24
Chapter 1. 1 to n bit numbers with no consecutive 1s in binary representation
Python3
25
Chapter 1. 1 to n bit numbers with no consecutive 1s in binary representation
C#
PHP
<?php
// Print all numbers upto n bits
// with no consecutive set bits.
function printNonConsecutive($n)
{
// Let us first compute
26
Chapter 1. 1 to n bit numbers with no consecutive 1s in binary representation
1 2 4 5
Source
https://www.geeksforgeeks.org/1-n-bit-numbers-no-consecutive-1s-binary-representation/
27
Chapter 2
Input : n = 4
Output : 1 2 4 5 8 9 10
These are numbers with 1 to 4
bits and no consecutive ones in
binary representation.
Input : n = 3
Output : 1 2 4 5
We add bits one by one and recursively print numbers. For every last bit, we have two
choices.
28
Chapter 2. 1 to n bit numbers with no consecutive 1s in binary representation.
1. We make a solution vector sol and insert first bit 1 in it which will be the first number.
2. Now we check whether length of solution vector is less than or equal to n or not.
3. If it is so then we calculate the decimal number and store it into a map as it store
numbers in sorted order.
4. Now we will have two conditions-
• if last digit in sol is 0 the we can insert 0 or 1 and recur.
• else if last digit is 1 then we can insert 0 only and recur.
numberWithNoConsecutiveOnes(n, sol)
{
if sol.size() <= n
29
Chapter 2. 1 to n bit numbers with no consecutive 1s in binary representation.
Output:
1 2 4 5 8 9 10
Related Post :
Count number of binary strings without consecutive 1’s
Improved By : Kishore Srinivas
30
Chapter 2. 1 to n bit numbers with no consecutive 1s in binary representation.
Source
https://www.geeksforgeeks.org/1-to-n-bit-numbers-with-no-consecutive-1s-in-binary-representation/
31
Chapter 3
2’s complement of a binary number is 1 added to the 1’s complement of the binary number.
Examples:
32
Chapter 3. 1’s and 2’s complement of a Binary Number
33
Chapter 3. 1’s and 2’s complement of a Binary Number
// Driver program
int main()
{
string bin = "1100";
printOneAndTwosComplement(bin);
return 0;
}
Output:
Related Post :
Efficient method for 2’s complement of a binary string
References:
http://qa.geeksforgeeks.org/6439/write-program-calculate-ones-and-twos-complement-of-number
http://geeksquiz.com/whats-difference-between-1s-complement-and-2s-complement/
Source
https://www.geeksforgeeks.org/1s-2s-complement-binary-number/
34
Chapter 4
35
Chapter 4. A Boolean Array Puzzle
Method 2
Method 3
This method doesn’t even need complement.
Method 4
Thanks to purvi for suggesting this method.
Source
https://www.geeksforgeeks.org/a-boolean-array-puzzle/
36
Chapter 5
A backtracking approach to
generate n bit Gray Codes
Input : 2
Output : 0 1 3 2
Explanation :
00 - 0
01 - 1
11 - 3
10 - 2
Input : 3
Output : 0 1 3 2 6 7 5 4
37
Chapter 5. A backtracking approach to generate n bit Gray Codes
/* we have 2 choices for each of the n bits either we
can include i.e invert the bit or we can exclude the
bit i.e we can leave the number as it is. */
void grayCodeUtil(vector<int>& res, int n, int& num)
{
// base case when we run out bits to process
// we simply include it in gray code sequence.
if (n == 0) {
res.push_back(num);
return;
}
// ignore the bit.
grayCodeUtil(res, n - 1, num);
// invert the bit.
num = num ^ (1 << (n - 1));
grayCodeUtil(res, n - 1, num);
}
// returns the vector containing the gray
// code sequence of n bits.
vector<int> grayCodes(int n)
{
vector<int> res;
// num is passed by reference to keep
// track of current code.
int num = 0;
grayCodeUtil(res, n, num);
return res;
}
// Driver function.
int main()
{
int n = 3;
vector<int> code = grayCodes(n);
for (int i = 0; i < code.size(); i++)
cout << code[i] << endl;
return 0;
}
Output:
38
Chapter 5. A backtracking approach to generate n bit Gray Codes
0
1
3
2
6
7
5
4
Source
https://www.geeksforgeeks.org/backtracking-approach-generate-n-bit-gray-codes/
39
Chapter 6
Input: 12
Output: 13
Input: 6
Output: 7
This question can be approached by using some bit magic. Following are different methods
to achieve the same using bitwise operators.
Method 1
To add 1 to a number x (say 0011000111), flip all the bits after the rightmost 0 bit (we get
0011000000). Finally, flip the rightmost 0 bit also (we get 0011001000) to get the answer.
C
40
Chapter 6. Add 1 to a given number
while( x & m )
{
x = x ^ m;
m <<= 1;
}
// flip the rightmost 0 bit
x = x ^ m;
return x;
}
/* Driver program to test above functions*/
int main()
{
printf("%d", addOne(13));
getchar();
return 0;
}
Java
41
Chapter 6. Add 1 to a given number
// This code is contributed by prerna saini.
Python3
C#
42
Chapter 6. Add 1 to a given number
PHP
<?php
// PHP code to add add
// one to a given number
function addOne($x)
{
$m = 1;
// Flip all the set bits
// until we find a 0
while( $x & $m )
{
$x = $x ^ $m;
$m <<= 1;
}
// flip the rightmost 0 bit
$x = $x ^ $m;
return $x;
}
// Driver Code
echo addOne(13);
// This code is contributed by vt_m.
?>
Output:
14
43
Chapter 6. Add 1 to a given number
Method 2
We know that the negative number is represented in 2’s complement form on most of the
architectures. We have the following lemma hold for 2’s complement representation of signed
numbers.
Say, x is numerical value of a number, then
~x = -(x+1) [ ~ is for bitwise complement ]
(x + 1) is due to addition of 1 in 2’s complement conversion
To get (x + 1) apply negation once again. So, the final expression becomes (-(~x)).
#include<stdio.h>
int addOne(int x)
{
return (-(~x));
}
/* Driver program to test above functions*/
int main()
{
printf("%d", addOne(13));
getchar();
return 0;
}
Java
44
Chapter 6. Add 1 to a given number
Python3
C#
// C# code to Add 1
// to a given number
using System;
class GFG
{
static int addOne(int x)
{
return (-(~x));
}
// Driver program
public static void Main()
{
Console.WriteLine(addOne(13));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Code to Add 1
// to a given number
function addOne($x)
{
return (-(~$x));
}
// Driver Code
45
Chapter 6. Add 1 to a given number
echo addOne(13);
// This code is contributed by vt_m.
?>
Output:
14
Example
Interpreting bits 1101 in 2’s complement form yields numerical value as -(2^4 – 13) = -3.
Applying ‘-‘ on the result leaves 3. Same analogy holds for decrement. Note that this
method works only if the numbers are stored in 2’s complement form.
Thanks to Venki for suggesting this method.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/add-1-to-a-given-number/
46
Chapter 7
Add minimum number to an array so that the sum becomes even - GeeksforGeeks
Given an array, write a program to add the minimum number(should be greater than 0)
to the array so that the sum of array becomes even.
Examples:
Input : 1 2 3 4 5 6 7 8
Output : 2
Explanation : Sum of array is 36, so we
add minimum number 2 to make the sum even.
Input : 1 2 3 4 5 6 7 8 9
Output : 1
Method 1 (Computing Sum). We calculate the sum of all elements of the array, then
we can check if the sum is even minimum number is 2, else minimum number is 1. This
method can cause overflow if sum exceeds allowed limit.
Method 2. Instead of calculating the sum of numbers, we keep the count of odd
number of elements in the array. If count of odd numbers present is even we return 2,
else we return 1.
For example – Array contains : 1 2 3 4 5 6 7
Odd number counts is 4. And we know that the sum of even numbers of odd number
is even. And sum of even number is always even (that is why, we don’t keep count of even
numbers).
47
Chapter 7. Add minimum number to an array so that the sum becomes even
C++
Java
48
Chapter 7. Add minimum number to an array so that the sum becomes even
}
// Driver method to test above function
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = arr.length;
System.out.println(minNum(arr, n));
}
}
Python
C#
49
Chapter 7. Add minimum number to an array so that the sum becomes even
PHP
<?php
// PHP program to add minimum number
// so that the sum of array becomes even
// Function to find out minimum number
function minNum( $arr, $n)
{
// Count odd number of
// terms in array
$odd = 0;
for ($i = 0; $i < $n; $i++)
if ($arr[$i] % 2)
$odd += 1;
return ($odd % 2)? 1 : 2;
}
// Driver code
$arr = array(1, 2, 3, 4, 5,
6, 7, 8, 9);
$n = count($arr);
echo minNum($arr, $n) ;
// This code is contributed by anuj_67.
50
Chapter 7. Add minimum number to an array so that the sum becomes even
?>
Output:
Method 3. We can also improve the 2 method, we don’t need to keep count of number
of odd elements present. We can take a boolean variable (initialized as 0). Whenever
we find the odd element in the array we perform the NOT(!) operation on the
boolean variable. This logical operator inverts the value of the boolean variable (meaning
if it is 0, it converts the variable to 1 and vice-versa).
For example – Array contains : 1 2 3 4 5
Explanation : variable initialized as 0.
Traversing the array
1 is odd, applying NOT operation in variable, now variable becomes 1.
2 is even, no operation.
3 is odd, applying NOT operation in variable, now variable becomes 0.
4 is even, no operation.
5 is odd, applying NOT operation in variable, now variable becomes 1.
If variable value is 1 it means odd number of odd elements are present, minimum
number to make sum of elements even is by adding 1.
Else minimum number is 2.
C++
51
Chapter 7. Add minimum number to an array so that the sum becomes even
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minNum(arr, n) << "n";
return 0;
}
Java
Python
52
Chapter 7. Add minimum number to an array so that the sum becomes even
C#
53
Chapter 7. Add minimum number to an array so that the sum becomes even
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to add minimum number
// so that the sum of array becomes even
// Function to find out minimum number
function minNum($arr, $n)
{
// Count odd number of
// terms in array
$odd = 0;
for($i = 0; $i < $n; $i++)
if ($arr[$i] % 2)
$odd = !$odd;
if ($odd)
return 1;
return 2;
}
// Driver code
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$n = sizeof($arr);
echo minNum($arr, $n) ,"\n";
// This code is contributed by nitin mittal
?>
Output :
Exercise :
Find the minimum number required to make the sum of elements odd.
Improved By : nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/add-minimum-number-to-an-array-so-that-the-sum-becomes-even/
54
Chapter 8
Since sizes of two strings may be different, we first make the size of smaller string equal to
that of bigger string by adding leading 0s. After making sizes same, we one by one add bits
from rightmost bit to leftmost bit. In every iteration, we need to sum 3 bits: 2 bits of 2
given strings and carry. The sum bit will be 1 if, either all of the 3 bits are set or one of
them is set. So we can do XOR of all bits to find the sum bit. How to find carry – carry will
be 1 if any of the two bits is set. So we can find carry by taking OR of all pairs. Following
is step by step algorithm.
1. Make them equal sized by adding 0s at the begining of smaller string.
2. Perform bit addition
…..Boolean expression for adding 3 bits a, b, c
…..Sum = a XOR b XOR c
…..Carry = (a AND b) OR ( b AND c ) OR ( c AND a )
Following is C++ implementation of the above algorithm.
#include <iostream>
using namespace std;
//adds the two bit strings and return the result
string addBitStrings( string first, string second );
// Helper method: given two unequal sized bit strings, converts them to
// same length by aadding leading 0s in the smaller string. Returns the
// the new length
int makeEqualLength(string &str1, string &str2)
{
55
Chapter 8. Add two bit strings
56
Chapter 8. Add two bit strings
Output:
Sum is 1100101
This article is compiled by Ravi Chandra Enaganti. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/add-two-bit-strings/
57
Chapter 9
58
Chapter 9. Add two numbers without using arithmetic operators
x = x ^ y;
// Carry is shifted by one so that adding
// it to x gives the required sum
y = carry << 1;
}
return x;
}
int main()
{
printf("%d", Add(15, 32));
return 0;
}
Java
59
Chapter 9. Add two numbers without using arithmetic operators
System.out.println(Add(15, 32));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
60
Chapter 9. Add two numbers without using arithmetic operators
PHP
<?php
// PHP Program to add two numbers
// without using arithmetic operator
function Add( $x, $y)
{
// Iterate till there is
// no carry
while ($y != 0)
{
// carry now contains common
//set bits of x and y
$carry = $x & $y;
// Sum of bits of x and y where at
//least one of the bits is not set
$x = $x ^ $y;
61
Chapter 9. Add two numbers without using arithmetic operators
Output :
47
Improved By : vt_m
Source
https://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/
62
Chapter 10
Examples :
Input : m = 456, n = 4
Output : 450
Algorithm :
Input n, m
while(n||m) { // Add each bits bit_sum = (n%10) + (m%10); // Neglect carry bit_sum
%= 10; // Update result // multiplier to maintain place value res = (bit_sum * multiplier)
+ res; n /= 10; m /= 10; // Update multiplier multiplier *=10; }
print res
Approach :
To solve this problem we will need the bit by bit addition of number where we start adding
two number from right most bit (LSB) and add integers from both nubers with same position.
63
Chapter 10. Addition of two numbers without carry
Also we will neglect carry at each position so that that carry will not affect further higher
bit position.
Start adding both numbers bit by bit and for each bit take sum of integers then neglect
their carry by taking modulo of bit_sum by 10 further add bit_sum to res by multiplying
bit_sum with a multiplier specifying place value. (Multiplier got incremented 10 times on
each iteration.)
C++
64
Chapter 10. Addition of two numbers without carry
return res;
}
// Driver program
int main()
{
int n = 8458;
int m = 8732;
cout << xSum(n, m);
return 0;
}
Java
65
Chapter 10. Addition of two numbers without carry
}
return res;
}
// Driver function
public static void main(String args[])
{
int n = 8458;
int m = 8732;
System.out.println(xSum(n, m));
}
}
/* This code is contributed by Sagar Shukla */
Python3
66
Chapter 10. Addition of two numbers without carry
C#
67
Chapter 10. Addition of two numbers without carry
break;
if (m == 0)
break;
}
return res;
}
// Driver function
public static void Main()
{
int n = 8458;
int m = 8732;
Console.WriteLine(xSum(n, m));
}
}
/* This code is contributed by Vt_m */
PHP
<?php
// php program for special
// addition of two number
function xSum($n, $m)
{
// variable to store result
$res = 0;
// variable to maintain
// place value
$multiplier = 1;
// variable to maintain
// each digit sum
$bit_sum;
// Add numbers till each
// number become zero
while ($n || $m) {
// Add each bits
$bit_sum = ($n % 10) +
($m % 10);
// Neglect carry
$bit_sum %= 10;
68
Chapter 10. Addition of two numbers without carry
// Update result
$res = ($bit_sum * $multiplier) + $res;
$n =floor($n / 10);
$m =floor($m / 10);
// Update multiplier
$multiplier *= 10;
}
return $res;
}
// Driver code
$n = 8458;
$m = 8732;
echo xSum($n, $m);
//This code is contributed by mits
?>
Output :
6180
Source
https://www.geeksforgeeks.org/special-addition-two-number/
69
Chapter 11
Input : n = 10, m = 11
Output : 11
Start from right of second number
Binary representation of n = 1 0 1 0
^ ^
Binary representation of m = 1 0 1 1
^ ^
Output is = 1 0 1 1
Input : n = 20, m = 7
Output : 5
Start from right of second number
binary representation of n = 1 0 1 0 0
^ ^
binary representation of m = 0 0 1 1 1
^ ^ ^
Output is = 0 0 1 0 1
Approach :-
1. Get the set even bits number of n.
70
Chapter 11. Alternate bits of two numbers to create a new number
C++
71
Chapter 11. Alternate bits of two numbers to create a new number
// return set even bit number
return (n & res);
}
// set odd bit of number m
int setoddbits(int m)
{
int count = 0;
// res for store 101010.. number
int res = 0;
// generate number form of 101010....
// till temp size
for (int temp = m; temp > 0; temp >>= 1) {
// if bit is even then generate
// number and or with res
if (count % 2 == 0)
res |= (1 << count);
count++;
}
// return set odd bit number
return (m & res);
}
int getAlternateBits(int n, int m)
{
// set even bit of number n
int tempn = setevenbits(n);
// set odd bit of number m
int tempm = setoddbits(m);
// take OR with these number
return (tempn | tempm);
}
// Driver code
int main()
{
int n = 10;
int m = 11;
// n = 1 0 1 0
72
Chapter 11. Alternate bits of two numbers to create a new number
// ^ ^
// m = 1 0 1 1
// ^ ^
// result= 1 0 1 1
cout << getAlternateBits(n, m);
return 0;
}
Java
73
Chapter 11. Alternate bits of two numbers to create a new number
// res for store 101010.. number
int res = 0;
// generate number form of 101010....
// till temp size
for (int temp = m; temp > 0; temp >>= 1)
{
// if bit is even then generate
// number and or with res
if (count % 2 == 0)
res |= (1 << count);
count++;
}
// return set odd bit number
return (m & res);
}
static int getAlternateBits(int n, int m)
{
// set even bit of number n
int tempn = setevenbits(n);
// set odd bit of number m
int tempm = setoddbits(m);
// take OR with these number
return (tempn | tempm);
}
// Driver code
public static void main (String[] args)
{
int n = 10;
int m = 11;
// n = 1 0 1 0
// ^ ^
// m = 1 0 1 1
// ^ ^
// result= 1 0 1 1
System.out.println(getAlternateBits(n, m));
}
}
74
Chapter 11. Alternate bits of two numbers to create a new number
Python3
75
Chapter 11. Alternate bits of two numbers to create a new number
temp >>= 1
# return set odd bit number
return (m & res)
def getAlternateBits(n, m):
# set even bit of number n
tempn = setevenbits(n)
# set odd bit of number m
tempm = setoddbits(m)
# take OR with these number
return (tempn | tempm)
# Driver code
n = 10
m = 11
# n = 1 0 1 0
# ^ ^
# m = 1 0 1 1
# ^ ^
# result= 1 0 1 1
print(getAlternateBits(n, m))
# This code is contributed by Ansu Kumari.
C#
76
Chapter 11. Alternate bits of two numbers to create a new number
77
Chapter 11. Alternate bits of two numbers to create a new number
PHP
<?php
// PHP Program to generate a number using
// alternate bits of two numbers.
// set even bit of number n
function setevenbits($n)
{
$temp = $n;
$count = 0;
// res for store 101010.. number
$res = 0;
// generate number form of 101010.....
// till temp size
for ($temp = $n; $temp > 0; $temp >>= 1)
{
// if bit is even then generate
// number and or with res
if ($count % 2 == 1)
$res |= (1 << $count);
$count++;
}
78
Chapter 11. Alternate bits of two numbers to create a new number
// return set even bit number
return ($n & $res);
}
// set odd bit of number m
function setoddbits($m)
{
$count = 0;
// res for store 101010.. number
$res = 0;
// generate number form of 101010....
// till temp size
for ($temp = $m; $temp > 0; $temp >>= 1)
{
// if bit is even then generate
// number and or with res
if ($count % 2 == 0)
$res |= (1 << $count);
$count++;
}
// return set odd bit number
return ($m & $res);
}
function getAlternateBits($n, $m)
{
// set even bit of number n
$tempn = setevenbits($n);
// set odd bit of number m
$tempm = setoddbits($m);
// take OR with these number
return ($tempn | $tempm);
}
// Driver code
$n = 10;
$m = 11;
// n = 1 0 1 0
// ^ ^
79
Chapter 11. Alternate bits of two numbers to create a new number
// m = 1 0 1 1
// ^ ^
// result= 1 0 1 1
echo getAlternateBits($n, $m);
// This code is contributed by mits
?>
Output :
11
Source
https://www.geeksforgeeks.org/alternate-bits-of-two-numbers-to-create-a-new-number/
80
Chapter 12
Given a natural number n. The task is to find the nth term of the Baum Sweet sequence,
i.e, check whether it contains any consecutive block of zeroes of odd length.
Input: n = 8
Output: 0
Explanations:
Binary representation of 8 is 1000. It
contains odd length block of consecutive 0s.
Therefore B8 is 0.
Input: n = 5
Output: 1
Input: n = 7
Output: 0
81
Chapter 12. Baum Sweet Sequence
The idea is to run a loop through the binary representation of n and count the length of all
the consecutive zero blocks present. If there is at-least one odd length zero block, then the
nth term for the given input n is 0 else it is 1.
82
Chapter 12. Baum Sweet Sequence
}
// Driver Code
int main()
{
int n = 8;
cout << nthBaumSweetSeq(n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/baum-sweet-sequence/
83
Chapter 13
1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF
bit = 2 ^ 0 (0th bit)
if NUM & bit == 1 means 0th bit is ON else 0th bit is OFF
Let us take unsigned integer (32 bit), which consist of 0-31 bits. To print binary represen-
tation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it
is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print
“1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation
of number.
void bin(unsigned n)
{
unsigned i;
for (i = 1 << 31; i > 0; i = i / 2)
(n & i)? printf("1"): printf("0");
84
Chapter 13. Binary representation of a given number
}
int main(void)
{
bin(7);
printf("\n");
bin(4);
}
Method 2: Recursive
Following is recursive method to print binary representation of ‘NUM’.
void bin(unsigned n)
{
/* step 1 */
if (n > 1)
bin(n/2);
/* step 2 */
printf("%d", n % 2);
}
int main(void)
{
bin(7);
printf("\n");
bin(4);
}
#include<bits/stdc++.h>
using namespace std;
85
Chapter 13. Binary representation of a given number
This article is compiled by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Improved By : TheNaiveKid
Source
https://www.geeksforgeeks.org/binary-representation-of-a-given-number/
86
Chapter 14
Binary representation of
previous number
Input : 10110
Output : 10101
Here n = (22)10 = (10110)2
Previous number = (21)10 = (10101)2
Input : 11000011111000000
Output : 11000011110111111
We store input as string so that large numbers can be handled. We traverse the string from
rightmost character and convert all 0’s to 1’s until we find a 1. Finally convert the found 1
to 0. The number so formed after this process is the required number. If input is “1”, then
previous number will be “0”. If only the first character in the entire string is ‘1’, then we
discard this character and change all the 0’s to 1’s.
87
Chapter 14. Binary representation of previous number
// binary representation
string previousNumber(string num)
{
int n = num.size();
// if the number is '1'
if (num.compare("1") == 0)
return "0";
// examine bits from right to left
int i;
for (i = n - 1; i >= 0; i--) {
// if '1' is encountered, convert
// it to '0' and then break
if (num.at(i) == '1') {
num.at(i) = '0';
break;
}
// else convert '0' to '1'
else
num.at(i) = '1';
}
// if only the 1st bit in the
// binary representation was '1'
if (i == 0)
return num.substr(1, n - 1);
// final binary representation
// of the required number
return num;
}
// Driver program to test above
int main()
{
string num = "10110";
cout << "Binary representation of previous number = "
<< previousNumber(num);
return 0;
}
Output:
88
Chapter 14. Binary representation of previous number
Source
https://www.geeksforgeeks.org/binary-representation-previous-number/
89
Chapter 15
Bit Fields in C
#include <stdio.h>
// A simple representation of date
struct date
{
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
The above representation of ‘date’ takes 12 bytes on a compiler where an unsigned int takes
4 bytes. Since we know that the value of d is always from 1 to 31, value of m is from 1 to
12, we can optimize the space using bit fields.
90
Chapter 15. Bit Fields in C
#include <stdio.h>
// A space optimized representation of date
struct date
{
// d has value between 1 and 31, so 5 bits
// are sufficient
unsigned int d: 5;
// m has value between 1 and 12, so 4 bits
// are sufficient
unsigned int m: 4;
unsigned int y;
};
int main()
{
printf("Size of date is %d bytes\n", sizeof(struct date));
struct date dt = {31, 12, 2014};
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
Output:
#include <stdio.h>
// A structure without forced alignment
struct test1
{
unsigned int x: 5;
unsigned int y: 8;
};
// A structure with forced alignment
struct test2
{
unsigned int x: 5;
unsigned int: 0;
91
Chapter 15. Bit Fields in C
unsigned int y: 8;
};
int main()
{
printf("Size of test1 is %d bytes\n", sizeof(struct test1));
printf("Size of test2 is %d bytes\n", sizeof(struct test2));
return 0;
}
Output:
2) We cannot have pointers to bit field members as they may not start at a byte boundary.
#include <stdio.h>
struct test
{
unsigned int x: 5;
unsigned int y: 5;
unsigned int z;
};
int main()
{
struct test t;
// Uncommenting the following line will make
// the program compile and run
printf("Address of t.x is %p", &t.x);
// The below line works fine as z is not a
// bit field member
printf("Address of t.z is %p", &t.z);
return 0;
}
Output:
92
Chapter 15. Bit Fields in C
#include <stdio.h>
struct test
{
unsigned int x: 2;
unsigned int y: 2;
unsigned int z: 2;
};
int main()
{
struct test t;
t.x = 5;
printf("%d", t.x);
return 0;
}
Output:
Implementation-Dependent
4) In C++, we can have static members in a structure/class, but bit fields cannot be static.
5) Array of bit fields is not allowed. For example, the below program fails in compilation.
struct test
{
unsigned int x[10]: 5;
};
93
Chapter 15. Bit Fields in C
int main()
{
}
Output:
Exercise:
Predict the output of following programs. Assume that unsigned int takes 4 bytes and long
int takes 8 bytes.
1)
#include <stdio.h>
struct test
{
unsigned int x;
unsigned int y: 33;
unsigned int z;
};
int main()
{
printf("%d", sizeof(struct test));
return 0;
}
2)
#include <stdio.h>
struct test
{
unsigned int x;
long int y: 33;
unsigned int z;
};
int main()
{
struct test t;
unsigned int *ptr1 = &t.x;
unsigned int *ptr2 = &t.z;
printf("%d", ptr2 - ptr1);
return 0;
}
94
Chapter 15. Bit Fields in C
3)
union test
{
unsigned int x: 3;
unsigned int y: 3;
int z;
};
int main()
{
union test t;
t.x = 5;
t.y = 4;
t.z = 1;
printf("t.x = %d, t.y = %d, t.z = %d",
t.x, t.y, t.z);
return 0;
}
4) Use bit fields in C to figure out a way whether a machine is little endian or big endian.
Source
https://www.geeksforgeeks.org/bit-fields-c/
95
Chapter 16
Logic: To clear all bits from LSB to i-th bit, we have to AND x with mask having LSB
to i-th bit 0. To obtain such mask, first left shift 1 i times. Now if we minus 1 from that,
all the bits from 0 to i-1 become 1 and remaining bits become 0. Now we can simply take
complement of mask to get all first i bits to 0 and remaining to 1.
Example-
x = 29 (00011101) and we want to clear LSB to 3rd bit, total 4 bits
mask -> 1 << 4 -> 16(00010000)
mask -> 16 – 1 -> 15(00001111)
mask -> ~mask -> 11110000
x & mask -> 16 (00010000)
2) Clearing all bits from MSB to i-th bit
96
Chapter 16. Bit Tricks for Competitive Programming
mask = (1 << i) - 1;
x &= mask;
Logic: To clear all bits from MSB to i-th bit, we have to AND x with mask having MSB
to i-th bit 0. To obtain such mask, first left shift 1 i times. Now if we minus 1 from that,
all the bits from 0 to i-1 become 1 and remaining bits become 0.
Example-
x = 215 (11010111) and we want to clear MSB to 4th bit, total 4 bits
mask -> 1 << 4 -> 16(00010000)
mask -> 16 – 1 -> 15(00001111)
x & mask -> 7(00000111)
3) Divide by 2
x >>= 1;
Logic: When we do arithmetic right shift, every bit is shifted to right and blank position is
substituted with sign bit of number, 0 in case of positive and 1 in case of negative number.
Since every bit is a power of 2, with each shift we are reducing the value of each bit by
factor of 2 which is equivalent to division of x by 2.
Example-
x = 18(00010010)
x >> 1 = 9 (00001001)
4) Multiplying by 2
x <<= 1;
Logic: When we do arithmetic left shift, every bit is shifted to left and blank position is
substituted with 0 . Since every bit is a power of 2, with each shift we are increasing the
value of each bit by a factor of 2 which is equivalent to multiplication of x by 2.
Example-
x = 18(00010010)
x << 1 = 36 (00100100)
5) Upper case English alphabet to lower case
ch |= ' ';
Logic: The bit representation of upper case and lower case English alphabets are –
97
Chapter 16. Bit Tricks for Competitive Programming
As we can see if we set 5th bit of upper case characters, it will be converted into lower case
character. We have to prepare a mask having 5th bit 1 and other 0 (00100000). This mask
is bit representation of space character (‘ ‘). The character ‘ch’ then ORed with mask.
Example-
ch = ‘A’ (01000001)
mask = ‘ ‘ (00100000)
ch | mask = ‘a’ (01100001)
Please refer Case conversion (Lower to Upper and Vice Versa) for details.
6) Lower case English alphabet to upper case
ch &= '_’ ;
Logic: The bit representation of upper case and lower case English alphabets are –
As we can see if we clear 5th bit of lower case characters, it will be converted into upper
case character. We have to prepare a mask having 5th bit 0 and other 1 (10111111). This
mask is bit representation of underscore character (‘_‘). The character ‘ch’ then AND with
mask.
Example-
ch = ‘a’ (01100001)
mask = ‘_ ‘ (11011111)
ch | mask = ‘A’ (01000001)
Please refer Case conversion (Lower to Upper and Vice Versa) for details.
7) Count set bits in integer
int countSetBits(int x)
{
int count = 0;
while (x)
{
98
Chapter 16. Bit Tricks for Competitive Programming
int log2(int x)
{
int res = 0;
while (x >>= 1)
res++;
return res;
}
Logic: We right shift x repeatedly until it becomes 0, meanwhile we keep count on the shift
operation. This count value is the log2(x).
9) Checking if given 32 bit integer is power of 2
int isPowerof2(int x)
{
return (x && !(x & x-1));
}
Logic: All the power of 2 have only single bit set e.g. 16 (00010000). If we minus 1 from
this, all the bits from LSB to set bit get toggled, i.e., 16-1 = 15 (00001111). Now if we AND
x with (x-1) and the result is 0 then we can say that x is power of 2 otherwise not. We have
to take extra care when x = 0.
Example
x = 16(000100000)
x – 1 = 15(00001111)
x & (x-1) = 0
so 16 is power of 2
Please refer this article for more bit hacks.
Source
https://www.geeksforgeeks.org/bit-tricks-competitive-programming/
99
Chapter 17
Problem Description:
100
Chapter 17. Bitmasking and Dynamic Programming | Set-2 (TSP)
The first part is to calculate the minimum distance between the two cells. We can do it by
simply using a BFS as all the distances are unit distance. To optimize our solution we will
be pre-calculating the distances taking the initial location and the location of the houses as
the source point for our BFS.
Each BFS traversal takes O(size of grid) time. Therefore, it is O(X * size_of_grid) for
overall pre-calculation, where X = number of houses + 1 (initial position)
Now lets’s think of a DP state
So we will be needing to track the visited houses and the last visited house to uniquely
identify a state in this problem.
Therefore, we will be taking dp[index][mask] as our DP state.
Here,
index : tells us the location of current house
mask : tells us the houses that are visited ( if ith bit is set in mask then this means that
the ith dirty tile is cleaned)
Whereas dp[index][mask] will tell us the minimum distance to visit X(number of set bits in
mask) houses corresponding to their order of their occurrence in the mask where the last
visited house is house at location index.
State transition relation
So our initial state will be dp[0][0] this tells that we are currently at initial tile that is our
initial location and mask is 0 that states that no house is visited till now.
And our final destination state will be dp[any index][LIMIT_MASK], here
LIMIT_MASK = (1<<N) – 1
and N = number of houses.
Therefore our DP state transition can be stated as
dp(curr_idx)(curr_mask) = min{
for idx : off_bits_in_curr_mask
dp(idx)(cur_mask.set_bit(idx)) + dist[curr_idx][idx]
}
The above relation can be visualized as the minimum distance to visit all the houses by
standing at curr_idx house and by already visiting cur_mask houses is equal to min of
distance between the curr_idx house and idx house + minimum distance to visit all the
houses by standing at idx house and by already
visiting ( cur_mask | (1 <<idx) ) houses.
So, here we iterate over all possible idx values such that cur_mask has ith bit as 0 that tells
us that ith house is not visited.
Whenever we have our mask = LIMIT_MASK, this means that we have visited all the
houses in the town. So, we will add the distance from the last visited town (i.e the town at
cur_idx positon) to the initial position (0, 0).
The C++ program for the above implementation is given below:
101
Chapter 17. Bitmasking and Dynamic Programming | Set-2 (TSP)
#include <bits/stdc++.h>
using namespace std;
#define INF 99999999
#define MAXR 12
#define MAXC 12
#define MAXMASK 2048
#define MAXHOUSE 12
// stores distance taking souce
// as every dirty tile
int dist[MAXR][MAXC][MAXHOUSE];
// memoization for dp states
int dp[MAXHOUSE][MAXMASK];
// stores coordinates for
// dirty tiles
vector < pair < int, int > > dirty;
// Directions
int X[] = {-1, 0, 0, 1};
int Y[] = {0, 1, -1, 0};
char arr[21][21];
// len : number of dirty tiles + 1
// limit : 2 ^ len -1
// r, c : number of rows and columns
int len, limit, r, c;
// Returns true if current position
// is safe to visit
// else returns false
// Time Complexity : O(1)
bool safe(int x, int y)
{
if (x >= r or y>= c or x<0 or y<0)
return false;
if (arr[x][y] == '#')
return false;
return true;
}
// runs BFS traversal at tile idx
// calulates distance to every cell
102
Chapter 17. Bitmasking and Dynamic Programming | Set-2 (TSP)
// in the grid
// Time Complexity : O(r*c)
void getDist(int idx){
// visited array to track visited cells
bool vis[21][21];
memset(vis, false, sizeof(vis));
// getting current positon
int cx = dirty[idx].first;
int cy = dirty[idx].second;
// initializing queue for bfs
queue < pair < int, int > > pq;
pq.push({cx, cy});
// initializing the dist to max
// because some cells cannot be visited
// by taking source cell as idx
for (int i = 0;i<= r;i++)
for (int j = 0;j<= c;j++)
dist[i][j][idx] = INF;
// base conditions
vis[cx][cy] = true;
dist[cx][cy][idx] = 0;
while (! pq.empty())
{
auto x = pq.front();
pq.pop();
for (int i = 0;i<4;i++)
{
cx = x.first + X[i];
cy = x.second + Y[i];
if (safe(cx, cy))
{
if (vis[cx][cy])
continue;
vis[cx][cy] = true;
dist[cx][cy][idx] = dist[x.first][x.second][idx] + 1;
pq.push({cx, cy});
}
}
}
}
// Dynamic Programming state transition recursion
103
Chapter 17. Bitmasking and Dynamic Programming | Set-2 (TSP)
104
Chapter 17. Bitmasking and Dynamic Programming | Set-2 (TSP)
105
Chapter 17. Bitmasking and Dynamic Programming | Set-2 (TSP)
// ...#...
// ...#.*.
// ...#...
// .*.#.*.
// ...#...
char Arr[5][7] = { {'.', '.', '.', '#', '.', '.', '.'},
{'.', '.', '.', '#', '.', '*', '.'},
{'.', '.', '.', '#', '.', '.', '.'},
{'.', '*', '.', '#', '.', '*', '.'},
{'.', '.', '.', '#', '.', '.', '.'}
};
r = 5; c = 7;
cout << "The given grid : " << endl;
for (int i = 0;i<r;i++)
{
for (int j = 0;j<c;j++)
{
cout << Arr[i][j] << " ";
arr[i][j] = Arr[i][j];
}
cout << endl;
}
// - initializitiation
// - precalculations
init();
ans = solve(0, 1);
cout << "Minimum distance for the given grid : ";
if (ans >= INF)
cout << "not possible" << endl;
else
cout << ans << endl;
return 0;
}
Output:
106
Chapter 17. Bitmasking and Dynamic Programming | Set-2 (TSP)
Note:
We have used the initial state to be dp[0][1] because we have pushed the start location at
the first position in the container of houses. Hence, our Bit Mask will be 1 as the 0th bit is
set i.e we have visited the starting location for our trip.
Time Complexity:
Consider the number of houses to be n. So, there are n * (2n ) states and at every state,
we are looping over n houses to transit over to next state and because of memoization we
are doing this looping transition only once for each state. Therefore, our Time Complexity
is O(n2 * 2n ).
Recommended:
• http://www.spoj.com/problems/CLEANRBT/
• https://www.youtube.com/watch?v=-JjA4BLQyqE
Source
https://www.geeksforgeeks.org/bitmasking-dynamic-programming-set-2-tsp/
107
Chapter 18
Input: 6
Output: 7
108
Chapter 18. Bits manipulation (Important tactics)
Output: 3
109
Chapter 18. Bits manipulation (Important tactics)
a ^= b;
b ^= a;
a ^= b;
Example :
Number = 23,
Binary form: 10111;
After flipping digits number will be: 01000;
Value: 11111 = 31;
9. We can find the most significant set bit in O(1) time for a fixed size integer. For
example below cocde is for 32 bit integer.
int setBitNumber(int n)
{
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n>>1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n>>2;
n |= n>>4;
n |= n>>8;
n |= n>>16;
// Increment n by 1 so that
// there is only one set bit
// which is just before original
// MSB. n now becomes 1000000000
110
Chapter 18. Bits manipulation (Important tactics)
n = n + 1;
// Return original MSB after shifting.
// n now becomes 100000000
return (n >> 1);
}
10. We can quickly check if bits in a number are in alternate pattern (like 101010). We
compute n ^ (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will
produce a number having set bits only. ‘^’ is a bitwise XOR operation. Refer check if
a number has bits in alternate pattern for details.
Source
https://www.geeksforgeeks.org/bits-manipulation-important-tactics/
111
Chapter 19
Input: L = 3, R = 8
Output: 15
3 | 4 | 5 | 6 | 7 | 8 = 15
Input: L = 12, R = 18
Output: 31
12 | 13 | 14 | 15 | 16 | 17 | 18 = 31
A naive approach is to traverse through all the integers between L and R and do bitwise
OR of all the numbers.
An efficient approach be to follow the following steps:
1. Find the position of Most Significant Bit (MSB) in both the numbers (L and R)
2. If the position of both MSBs are different, set all the bits from the max(MSB1, MSB2)
including this different bit upto Oth bit i.e. add the value (1 << i) for all 0 � i �
max(MSB1, MSB2) in the answer.
3. If the position of both MSBs are same, then
• Set this bit corresponding to MSB or add the value (1 << MSB) in the answer.
• Subtract the value (1 << MSB) from both the numbers (L and R).
• Repeat the steps 1, 2 and 3.
Given below is the working of the above algorithm when L = 18 and R = 21.
112
Chapter 19. Bitwise OR (or | ) of a range
L = 18, R = 21
The result is initially 0.
The position of Most Significant Bit in L = 4
Position of Most Significant Bit in R = 4
Since positions are same, add value (1 << 4) i.e. 16 to the result.
C++
113
Chapter 19. Bitwise OR (or | ) of a range
// Find the MSB position in R
int msb_p2 = MSBPosition(R);
while (msb_p1 == msb_p2) {
long long int res_val = (1 << msb_p1);
// Add this value until msb_p1 and
// msb_p2 are same;
res += res_val;
L -= res_val;
R -= res_val;
// Calculate msb_p1 and msb_p2
msb_p1 = MSBPosition(L);
msb_p2 = MSBPosition(R);
}
// Find the max of msb_p1 and msb_p2
msb_p1 = max(msb_p1, msb_p2);
// Set all the bits from msb_p1 upto
// 0th bit in the result
for (int i = msb_p1; i >= 0; i--) {
long long int res_val = (1 << i);
res += res_val;
}
return res;
}
// Driver Code
int main()
{
int L = 12, R = 18;
cout << findBitwiseOR(L, R) << endl;
return 0;
}
Java
114
Chapter 19. Bitwise OR (or | ) of a range
115
Chapter 19. Bitwise OR (or | ) of a range
msb_p1 = Math.max(msb_p1,
msb_p2);
// Set all the bits
// from msb_p1 upto
// 0th bit in the result
for (int i = msb_p1; i >= 0; i--)
{
long res_val = (1 << i);
res += res_val;
}
return res;
}
// Driver Code
public static void main (String[] args)
{
int L = 12, R = 18;
System.out.println(findBitwiseOR(L, R));
}
}
// This code is contributed
// by anuj_67.
C#
// C# Program to find
// the bitwise OR of all
// the intgers in range L-R
using System;
class GFG
{
// Returns the Most Significant
// Bit Position (MSB)
static int MSBPosition(long N)
{
int msb_p = -1;
while (N > 0)
{
N = N >> 1;
msb_p++;
}
return msb_p;
}
116
Chapter 19. Bitwise OR (or | ) of a range
117
Chapter 19. Bitwise OR (or | ) of a range
// Driver Code
public static void Main ()
{
int L = 12, R = 18;
Console.WriteLine(findBitwiseOR(L, R));
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP Program to find the
// bitwise OR of all the
// intgers in range L-R
// Returns the Most Significant
// Bit Position (MSB)
function MSBPosition($N)
{
$msb_p = -1;
while ($N)
{
$N = $N >> 1;
$msb_p++;
}
return $msb_p;
}
// Returns the Bitwise
// OR of all integers
// between L and R
function findBitwiseOR($L, $R)
{
$res = 0;
// Find the MSB
// position in L
$msb_p1 = MSBPosition($L);
// Find the MSB
// position in R
$msb_p2 = MSBPosition($R);
while ($msb_p1 == $msb_p2)
118
Chapter 19. Bitwise OR (or | ) of a range
{
$res_val = (1 << $msb_p1);
// Add this value until
// msb_p1 and msb_p2 are same;
$res += $res_val;
$L -= $res_val;
$R -= $res_val;
// Calculate msb_p1
// and msb_p2
$msb_p1 = MSBPosition($L);
$msb_p2 = MSBPosition($R);
}
// Find the max of
// msb_p1 and msb_p2
$msb_p1 = max($msb_p1,
$msb_p2);
// Set all the bits from msb_p1
// upto 0th bit in the result
for ($i = $msb_p1; $i >= 0; $i--)
{
$res_val = (1 << $i);
$res += $res_val;
}
return $res;
}
// Driver Code
$L = 12; $R = 18;
echo findBitwiseOR($L, $R);
// This code is contributed
// by anuj_67.
?>
Output:
31
119
Chapter 19. Bitwise OR (or | ) of a range
Source
https://www.geeksforgeeks.org/bitwise-or-or-of-a-range/
120
Chapter 20
121
Chapter 20. Bitwise Operators in C/C++
return 0;
}
Output:
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4
The following are many other interesting problems which can be used using XOR operator.
Find the Missing Number, swap two numbers without using a temporary variable, A Memory
Efficient Doubly Linked List, and Find the two non-repeating elements. There are many
more (See this, this, this, this, this and this)
3) The bitwise operators should not be used in place of logical operators.
The result of logical operators (&&, || and !) is either 0 or 1, but bitwise operators return an
122
Chapter 20. Bitwise Operators in C/C++
integer value. Also, the logical operators consider any non-zero operand as 1. For example,
consider the following program, the results of & and && are different for same operands.
int main()
{
int x = 2, y = 5;
(x & y)? printf("True ") : printf("False ");
(x && y)? printf("True ") : printf("False ");
return 0;
}
// Output: False True
int main()
{
int x = 19;
printf ("x << 1 = %d\n", x << 1);
printf ("x >> 1 = %d\n", x >> 1);
return 0;
}
// Output: 38 9
5) The & operator can be used to quickly check if a number is odd or even
The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value
would be zero.
int main()
{
int x = 19;
(x & 1)? printf("Odd"): printf("Even");
return 0;
}
// Output: Odd
123
Chapter 20. Bitwise Operators in C/C++
unsigned int x = 1;
printf("Signed Result %d \n", ~x);
printf("Unsigned Result %ud \n", ~x);
return 0;
}
/* Output:
Signed Result -2
Unsigned Result 4294967294d */
Important Links :
Source
https://www.geeksforgeeks.org/bitwise-operators-in-c-cpp/
124
Chapter 21
Bitwise Sieve
Input : 30
Output : 2 3 5 7 11 13 17 19 23 29
Input : n = 100
Output : 2 3 5 7 11 13 17 19 23 29 31 37
41 43 47 53 59 61 67 71 73 79 83
89 97
We know how to calculate all primes less than n by Sieve of Eratosthenes. Below is an
implementation of Sieve.
One optimization in below implementation is, we have skipped all even numbers
altogether.
We reduce size of prime array to half. We also reduce all iterations to half.
C++
125
Chapter 21. Bitwise Sieve
Java
126
Chapter 21. Bitwise Sieve
Arrays.fill(prime, false);
// 2 is the only even prime so we can
// ignore that. Loop starts from 3.
for (int i = 3 ; i * i < n; i += 2)
{
// If i is prime, mark all its
// multiples as composite
if (prime[i / 2] == false)
for (int j = i * i; j < n; j += i * 2)
prime[j / 2] = true;
}
// writing 2 separately
System.out.print("2 ");
// Printing other primes
for (int i = 3; i < n ; i += 2)
if (prime[i / 2] == false)
System.out.print(i + " ");
}
public static void main (String[] args)
{
int n = 100 ;
normalSieve(n);
}
}
// This code is contributed by Anant Agarwal.
C#
127
Chapter 21. Bitwise Sieve
PHP
<?php
// PHP program to implement normal
// Sieve of Eratosthenes using
// simple optimization to reduce
// size of prime array to half and
// reducing iterations.
function normalSieve($n)
128
Chapter 21. Bitwise Sieve
{
// prime[i] is going to store
// true if if i*2 + 1 is composite.
$prime = array_fill(0, (int)($n / 2),
false);
// 2 is the only even prime so
// we can ignore that. Loop
// starts from 3.
for ($i = 3 ; $i * $i < $n; $i += 2)
{
// If i is prime, mark all its
// multiples as composite
if ($prime[$i / 2] == false)
for ($j = $i * $i; $j < $n;
$j += $i * 2)
$prime[$j / 2] = true;
}
// writing 2 separately
echo "2 ";
// Printing other primes
for ($i = 3; $i < $n ; $i += 2)
if ($prime[$i / 2] == false)
echo $i . " ";
}
// Driver code
$n = 100 ;
normalSieve($n);
// This code is contributed by mits.
?>
Output :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
C++
129
Chapter 21. Bitwise Sieve
130
Chapter 21. Bitwise Sieve
Java
131
Chapter 21. Bitwise Sieve
{
// Assuming that n takes 32 bits,
// we reduce size to n/64 from n/2.
int prime[] = new int[n/64 + 1];
// 2 is the only even prime so we
// can ignore that loop starts from
// 3 as we have used in sieve of
// Eratosthenes .
for (int i = 3; i * i <= n; i += 2) {
// If i is prime, mark all its
// multiples as composite
if (ifnotPrime(prime, i)==0)
for (int j = i * i, k = i << 1;
j < n; j += k)
makeComposite(prime, j);
}
// writing 2 separately
System.out.printf("2 ");
// Printing other primes
for (int i = 3; i <= n; i += 2)
if (ifnotPrime(prime, i) == 0)
System.out.printf("%d ", i);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 30;
bitWiseSieve(n);
}
}
// This code is contributed by Arnav Kr. Mandal.
C#
// C# Code to implement Bitwise
// Sieve of Eratosthenes.
using System;
class GFG
{
// Checks whether x is
// prime or composite
132
Chapter 21. Bitwise Sieve
<?php
// PHP program to implement
// bitwise Sieve of Eratosthenes.
$prime;
133
Chapter 21. Bitwise Sieve
// Checks whether x is
// prime or composite
function ifnotPrime($x)
{
global $prime;
// checking whether the value
// of element is set or not.
// Using prime[x/64], we find
// the slot in prime array.
// To find the bit number, we
// divide x by 2 and take its
// mod with 32.
return $a = ($prime[(int)($x / 64)] &
(1 << (($x >> 1) & 31)));
}
// Marks x composite in prime[]
function makeComposite($x)
{
global $prime;
// Set a bit corresponding to
// given element. Using prime[x/64],
// we find the slot in prime
// array. To find the bit number,
// we divide x by 2 and take its
// mod with 32.
$prime[(int)($x / 64)] |=
(1 << (($x >> 1) & 31));
}
// Prints all prime
// numbers smaller than n.
function bitWiseSieve($n)
{
global $prime;
// Assuming that n takes
// 32 bits, we reduce
// size to n/64 from n/2.
// Initializing values to 0 .
$prime = array_fill(0,
(int)ceil($n / 64), 0);
// 2 is the only even prime
// so we can ignore that
// loop starts from 3 as we
134
Chapter 21. Bitwise Sieve
Output:
2 3 5 7 11 13 17 19 23 29
Source
https://www.geeksforgeeks.org/bitwise-sieve/
135
Chapter 22
Input : x = 12, y = 15
Output : 12
12 & 13 & 14 & 14 = 12
Input : x = 10, y = 20
Output : 0
A simple solution is to traverse all numbers from x to y and do bit-wise and of all numbers
in range.
An efficient solution is to follow following steps.
1) Find position of Most Significant Bit (MSB) in both numbers.
2) If positions of MSB are different, then result is 0.
3) If positions are same. Let positions be msb_p.
……a) We add 2msb_p to result.
……b) We subtract 2msb_p from x and y,
……c) Repeat steps 1, 2 and 3 for new values of x and y.
Example 1 :
x = 10, y = 20
Result is initially 0.
Position of MSB in x = 3
Position of MSB in y = 4
Since positions are different, return result.
136
Chapter 22. Bitwise and (or &) of a range
Example 2 :
x = 17, y = 19
Result is initially 0.
Position of MSB in x = 4
Position of MSB in y = 4
Since positions are same, we compute 24.
We add 24 to result.
Result becomes 16.
C++
137
Chapter 22. Bitwise and (or &) of a range
while (x && y)
{
// Find positions of MSB in x and y
int msb_p1 = msbPos(x);
int msb_p2 = msbPos(y);
// If positions are not same, return
if (msb_p1 != msb_p2)
break;
// Add 2^msb_p1 to result
ll msb_val = (1 << msb_p1);
res = res + msb_val;
// subtract 2^msb_p1 from x and y.
x = x - msb_val;
y = y - msb_val;
}
return res;
}
// Driver code
int main()
{
ll x = 10, y = 15;
cout << andOperator(x, y);
return 0;
}
Java
138
Chapter 22. Bitwise and (or &) of a range
return msb_p;
}
// Function to find Bit-wise & of all
// numbers from x to y.
static long andOperator(long x, long y)
{
long res = 0; // Initialize result
while (x > 0 && y > 0) {
// Find positions of MSB in x and y
int msb_p1 = msbPos(x);
int msb_p2 = msbPos(y);
// If positions are not same, return
if (msb_p1 != msb_p2)
break;
// Add 2^msb_p1 to result
long msb_val = (1 << msb_p1);
res = res + msb_val;
// subtract 2^msb_p1 from x and y.
x = x - msb_val;
y = y - msb_val;
}
return res;
}
// Driver code
public static void main(String[] args)
{
long x = 10, y = 15;
System.out.print(andOperator(x, y));
}
}
// This code is contributed by Anant Agarwal.
Python3
139
Chapter 22. Bitwise and (or &) of a range
C#
140
Chapter 22. Bitwise and (or &) of a range
141
Chapter 22. Bitwise and (or &) of a range
return res;
}
// Driver code
public static void Main()
{
long x = 10, y = 15;
Console.WriteLine(andOperator(x, y));
}
}
// This code is contributed by Anant Agarwal.
Output:
NOTE: We are not considering inclusive range so if the number is ’a’ we shouldn’t flip
anymore i.e.’a’ will be the answer.
Example 1 :
x = 10, y = 20
y = 10100
Flip LSB of y New Number = 10000 i.e. 16
16 is in range so Again flip : 00000 i.e. 0 and 0 is not in range so 0 is the answer.
Example 2 :
x = 17, y = 19
y = 10011
Flip LSB of y so New Number = 10010 i.e. 18
18 is in range so Again flip : 10000 i.e. 16 and 16 is 'a' so Stop , answer is 16.
142
Chapter 22. Bitwise and (or &) of a range
using namespace std;
ll andOperator(ll a, ll b){
while(a < b){
// -b is the 2's complement of b when do bitwise or with b
//we get LSB and we subtract that from b
b -= (b & -b);
}
return b;
}
// Driver code
int main(){
ll a, b;
a = 10; b = 15;
cout << andOperator(a, b);
}
Output:
Source
https://www.geeksforgeeks.org/bitwise-and-or-of-a-range/
143
Chapter 23
Input : int x = 4, y = 78
Output : 82
Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be
obtained by performing AND (&) of two bits.
Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this
logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^)
of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&)
is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it
to x ^ y to get the required result.
One important observation is, if (x & y) becomes 0, then result is x ^ y.
C
144
Chapter 23. Bitwise recursive addition of two integers
Java
145
Chapter 23. Bitwise recursive addition of two integers
C#
// C# program to do recursive
// addition of two integers
using System;
class GFG {
static int add(int x, int y)
{
int keep = (x & y) << 1;
int res = x^y;
// If bitwise & is 0, then there
// is not going to be any carry.
// Hence result of XOR is addition.
if (keep == 0)
return res;
return add(keep, res);
}
// Driver code
public static void Main ()
{
Console.Write(add(15, 38));
}
}
// This code is contributed by Smitha.
PHP
<?php
// php program to do recursive addition
// of two integers
function add($x, $y) {
$keep = ($x & $y) << 1;
$res = $x^$y;
// If bitwise & is 0, then there
// is not going to be any carry.
// Hence result of XOR is addition.
if ($keep == 0)
146
Chapter 23. Bitwise recursive addition of two integers
{
echo $res;
exit(0);
}
add($keep, $res);
}
// Driver code
$k= add(15, 38);
// This code is contributed by mits.
?>
Output:
53
Source
https://www.geeksforgeeks.org/bitwise-recursive-addition-two-integers/
147
Chapter 24
class Test {
public static void main(String args[]) {
int x = -4;
System.out.println(x>>1);
int y = 4;
System.out.println(y>>1);
}
}
Output:
-2
2
2) >>> (Unsigned right shift) In Java, the operator ‘>>>’ is unsigned right shift
operator. It always fills 0 irrespective of the sign of the number.
148
Chapter 24. Bitwise right shift operators in Java
class Test {
public static void main(String args[]) {
// x is stored using 32 bit 2's complement form.
// Binary representation of -1 is all 1s (111..1)
int x = -1;
System.out.println(x>>>29); // The value of 'x>>>29' is 00...0111
System.out.println(x>>>30); // The value of 'x>>>30' is 00...0011
System.out.println(x>>>31); // The value of 'x>>>31' is 00...0001
}
}
Output:
7
3
1
Improved By : nagen010
Source
https://www.geeksforgeeks.org/bitwise-shift-operators-in-java/
149
Chapter 25
Booth’s Multiplication
Algorithm
Examples:
Result=1100
Algorithm :
150
Chapter 25. Booth’s Multiplication Algorithm
C++
151
Chapter 25. Booth’s Multiplication Algorithm
152
Chapter 25. Booth’s Multiplication Algorithm
temp = 1;
}
// THIRD CONDITION
else if (temp == 1)
{
// add BR to accumulator
add(ac, br, qrn);
cout << "\t\tA = A + BR\t";
for (int i = qrn - 1; i >= 0; i--)
cout << ac[i];
temp = 0;
}
cout << "\n\t";
rightShift(ac, qr, qn, qrn);
}
// FIRST CONDITION
else if (qn - qr[0] == 0)
rightShift(ac, qr, qn, qrn);
display(ac, qr, qrn);
cout << "\t";
// decrement counter
sc--;
cout << "\t" << sc << "\n";
}
}
// driver code
int main(int argc, char** arg)
{
int mt[10], sc;
int brn, qrn;
// Number of multiplicand bit
brn = 4;
// multiplicand
int br[] = { 0, 1, 1, 0 };
// copy multiplier to temp array mt[]
for (int i = brn - 1; i >= 0; i--)
mt[i] = br[i];
153
Chapter 25. Booth’s Multiplication Algorithm
reverse(br, br + brn);
complement(mt, brn);
// No. of multiplier bit
qrn = 4;
// sequence counter
sc = qrn;
// multiplier
int qr[] = { 1, 0, 1, 0 };
reverse(qr, qr + qrn);
boothAlgorithm(br, qr, mt, qrn, sc);
cout << endl
<< "Result = ";
for (int i = qrn - 1; i >= 0; i--)
cout << qr[i];
}
C#
// C# code to implement
// booth's algorithm
using System;
class GFG
{
// function to perform
// adding in the accumulator
static void add(int []ac,
int []x,
int qrn)
{
int i, c = 0;
for (i = 0; i < qrn; i++)
{
// updating accumulator
// with A = A + BR
ac[i] = ac[i] + x[i] + c;
if (ac[i] > 1)
154
Chapter 25. Booth’s Multiplication Algorithm
{
ac[i] = ac[i] % 2;
c = 1;
}
else
c = 0;
}
}
// function to find
// the number's complement
static void complement(int []a, int n)
{
int i;
int []x = new int[8];
Array.Clear(x, 0, 8);
x[0] = 1;
for (i = 0; i < n; i++)
{
a[i] = (a[i] + 1) % 2;
}
add(a, x, n);
}
// function to perform
// right shift
static void rightShift(int []ac, int []qr,
ref int qn, int qrn)
{
int temp, i;
temp = ac[0];
qn = qr[0];
Console.Write("\t\trightShift\t");
for (i = 0; i < qrn - 1; i++)
{
ac[i] = ac[i + 1];
qr[i] = qr[i + 1];
}
qr[qrn - 1] = temp;
}
// function to display
// operations
static void display(int []ac,
155
Chapter 25. Booth’s Multiplication Algorithm
int []qr,
int qrn)
{
int i;
// accumulator content
for (i = qrn - 1; i >= 0; i--)
Console.Write(ac[i]);
Console.Write("\t");
// multiplier content
for (i = qrn - 1; i >= 0; i--)
Console.Write(qr[i]);
}
// Function to implement
// booth's algo
static void boothAlgorithm(int []br, int []qr,
int []mt, int qrn,
int sc)
{
int qn = 0;
int []ac = new int[10];
Array.Clear(ac, 0, 10);
int temp = 0;
Console.Write("qn\tq[n + 1]\tBR\t" +
"\tAC\tQR\t\tsc\n");
Console.Write("\t\t\tinitial\t\t");
display(ac, qr, qrn);
Console.Write("\t\t" + sc + "\n");
while (sc != 0)
{
Console.Write(qr[0] + "\t" + qn);
// SECOND CONDITION
if ((qn + qr[0]) == 1)
{
if (temp == 0)
{
// subtract BR
// from accumulator
add(ac, mt, qrn);
Console.Write("\t\tA = A - BR\t");
156
Chapter 25. Booth’s Multiplication Algorithm
for (int i = qrn - 1; i >= 0; i--)
Console.Write(ac[i]);
temp = 1;
}
// THIRD CONDITION
else if (temp == 1)
{
// add BR to accumulator
add(ac, br, qrn);
Console.Write("\t\tA = A + BR\t");
for (int i = qrn - 1; i >= 0; i--)
Console.Write(ac[i]);
temp = 0;
}
Console.Write("\n\t");
rightShift(ac, qr, ref qn, qrn);
}
// FIRST CONDITION
else if (qn - qr[0] == 0)
rightShift(ac, qr,
ref qn, qrn);
display(ac, qr, qrn);
Console.Write("\t");
// decrement counter
sc--;
Console.Write("\t" + sc + "\n");
}
}
// Driver code
static void Main()
{
int []mt = new int[10];
int sc, brn, qrn;
// Number of
// multiplicand bit
brn = 4;
// multiplicand
157
Chapter 25. Booth’s Multiplication Algorithm
Output :
qn q[n + 1] BR AC QR sc
initial 0000 1010 4
0 0 rightShift 0000 0101 3
1 0 A = A - BR 1010
rightShift 1101 0010 2
0 1 A = A + BR 0011
rightShift 0001 1001 1
1 0 A = A - BR 1011
158
Chapter 25. Booth’s Multiplication Algorithm
Result = 1100
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/booths-multiplication-algorithm/
159
Chapter 26
if x = 4
binary value of 4 is 100
Output: No of ones is 1.
Output:
Count of 1s in binary of 5 is 2
160
Chapter 26. Builtin functions of GCC compiler
if x = 7
7 has odd no. of 1's in its binary(111).
Output: Parity of 7 is 1
Output:
Parity of 7 is 1
3. __builtin_clz(x): This function is used to count the leading zeros of the integer.
Note : clz = count leading zero’s
Example: It counts number of zeros before the first occurence of one(set bit).
a = 16
Binary form of 16 is 00000000 00000000 00000000 00010000
Output: 27
Output:
161
Chapter 26. Builtin functions of GCC compiler
a = 16
Binay form of 16 is 00000000 00000000 00000000 00010000
Output: ctz = 4
Output:
Source
https://www.geeksforgeeks.org/builtin-functions-gcc-compiler/
162
Chapter 27
163
Chapter 27. C++ bitset and its application
164
Chapter 27. C++ bitset and its application
// bset.set() sets all bits
cout << set8.set() << endl;
// bset.set(pos, b) makes bset[pos] = b
cout << set8.set(4, 0) << endl;
// bset.set(pos) makes bset[pos] = 1 i.e. default
// is 1
cout << set8.set(4) << endl;
// reset function makes all bits 0
cout << set8.reset(2) << endl;
cout << set8.reset() << endl;
// flip function flips all bits i.e. 1 <-> 0
// and 0 <-> 1
cout << set8.flip(2) << endl;
cout << set8.flip() << endl;
// Converting decimal number to binary by using bitset
int num = 100;
cout << "\nDecimal number: " << num
<< " Binary equivalent: " << bitset<8>(num);
return 0;
}
Output :
00000000000000000000000000000000
00000000000000000000000000010100
00000000000000000000000000001100
00010010
00010010 has 2 ones and 6 zeros
bool representation of 00010010 : 0 1 0 0 1 0 0 0
bset1 has no bit set.
11111111
11101111
11111111
11111011
00000000
00000100
11111011
165
Chapter 27. C++ bitset and its application
For bitset set, reset and flip function are defined. Set function sets (1) all bits of bitset if
no argument is provided otherwise it sets the bit whose position is given as argument. In
same way reset and flip also work if they are called with no argument they perform their
operation on whole bitset and if some position is provided as argument then they perform
operation at that position only.
For bitset all bitwise operator are overloaded that is they can be applied to bitset directly
without any casting or conversion, main overloaded operator are &, |, ==, != and shifting
operator <> which makes operation on bitset easy.
Use of above operator is shown in below code.
Output :
0
1
1010
0010
166
Chapter 27. C++ bitset and its application
0011
1100
0110
1100
0010
0111
0101
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : gaurav1614
Source
https://www.geeksforgeeks.org/c-bitset-and-its-application/
167
Chapter 28
Output:
168
Chapter 28. C++ bitset interesting facts
00110010
00000010
00000001
We can construct a bitset using the characters in the std::basic_string _str. An optional
starting position _pos and length _n can be provided, as well as characters denoting alter-
nate values for set (_one) and unset (_zero) bits.
Syntax:
Output:
01001101
Constructs an object of class bitset, initializing the N bits to values that correspond to the
characters provided in a c-style character string of zeros and ones. You call the constructor
without casting the string into a string type. It also has two optional parameters, _Zero
and _One, which indicate what character in _Str is to be interpreted to mean a 0 bit and
a 1 bit, respectively.
169
Chapter 28. C++ bitset interesting facts
#include <bitset>
#include <iostream>
int main()
{
// char* constructor using custom digits
std::bitset<8> b1("XXXXYYYY", 8, 'X', 'Y'); // [0, 0, 0, 0, 1, 1, 1, 1]
std::cout << b1 << '\n';
}
Output:
00001111
Bitset Operations
1. std::bitset::to_string()
Converts the contents of the bitset to a string. Uses zero to represent bits with value
of false and one to represent bits with value of true. The resulting string contains
N characters with the first character corresponds to the last (N-1th) bit and the last
character corresponding to the first bit. Also, we can pass the characters used to print
true and false value through the parameters.
Example:
Output:
00101010
**1*1*1*
OOXOXOXO
170
Chapter 28. C++ bitset interesting facts
2. std::bitset::to_ulong():
Converts the contents of the bitset to an unsigned long integer. The first bit of
the bitset corresponds to the least significant digit of the number and the last bit
corresponds to the most significant digit. Function throws std::overflow_error if the
value cannot be represented in unsigned long.
Example:
Output:
Source
https://www.geeksforgeeks.org/c-bitset-interesting-facts/
171
Chapter 29
CHAR_BIT in C
CHAR_BIT in C - GeeksforGeeks
CHAR_BIT : It is the number of bits in char. These days, almost all architectures use 8
bits per byte (But it is not the case always, some older machines used to have 7-bit byte).
It can be found in
Let us see an application of it. Suppose we wish to print byte by byte representation of an
integer.
Examples :
Input : 4
Output : 00000000 00000000 00000000 00000100
Input : 12
Output : 00000000 00000000 00000000 00001100
172
Chapter 29. CHAR_BIT in C
{
cout << s.top();
s.pop();
// Put a space after every byte.
if (i % CHAR_BIT == 0)
cout << " ";
}
}
int main()
{
int num = 12;
printInBinary(num);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/char_bit-in-c/
173
Chapter 30
CPP
174
Chapter 30. Calculate 7n/8 without using division and multiplication operators
int main()
{
unsigned int n = 9;
printf("%d", multiplyBySevenByEight(n));
return 0;
}
Java
Python3
175
Chapter 30. Calculate 7n/8 without using division and multiplication operators
print(multiplyBySevenByEight(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
PHP
<?php
// PHP program to evaluate ceil
// (7n/8) without using * and
function multiplyBySevenByEight( $n)
{
// Note the inner bracket here.
// This is needed because
// precedence of '-' operator
// is higher than '<<'
176
Chapter 30. Calculate 7n/8 without using division and multiplication operators
Output :
C++
Java
177
Chapter 30. Calculate 7n/8 without using division and multiplication operators
class GFG
{
static int multiplyBySevenByEight(int n)
{
// Step 1) First multiply number
// by 7 i.e. 7n = (n << 3) -n
// * Step 2) Divide result by 8
return ((n << 3) -n) >> 3;
}
// Driver program
public static void main(String args[])
{
int n = 15;
System.out.println(multiplyBySevenByEight(n));
}
}
// This code is contributed by Anshika Goyal.
Python3
C#
178
Chapter 30. Calculate 7n/8 without using division and multiplication operators
static int multiplyBySevenByEight(int n)
{
// Step 1) First multiply number
// by 7 i.e. 7n = (n << 3) -n
// * Step 2) Divide result by 8
return ((n << 3) -n) >> 3;
}
// Driver program
public static void Main()
{
int n = 15;
Console.WriteLine(
multiplyBySevenByEight(n));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to evaluate 7n/8
// without using * and /
function multiplyBySevenByEight( $n)
{
/* Step 1) First multiply number by
7 i.e. 7n = (n << 3) - n
Step 2) Divide result by 8 */
return (($n << 3) -$n) >> 3;
}
// Driver Code
$n = 15;
echo multiplyBySevenByEight($n);
// This code is contributed by anuj_67.
?>
Output :
13
179
Chapter 30. Calculate 7n/8 without using division and multiplication operators
Note : There is difference between outcomes of two methods. The method 1 produces
ceil(7n/8), but method two produces integer value of 7n/8. For example, for n = 15, outcome
of first method is 14, but for second method is 13.
Thanks to Narendra Kangralkar for suggesting this method.
This article is contributed by Rajeev. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : Sam007, jit_t, vt_m
Source
https://www.geeksforgeeks.org/calculate-7n8-without-using-division-and-multiplication-operators/
180
Chapter 31
Input : n = 6
Output : 7
// 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 = 7
Input : n = 7
Output : 0
// 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 = 0
181
Chapter 31. Calculate XOR from 1 to n.
Java
182
Chapter 31. Calculate XOR from 1 to n.
Python 3
183
Chapter 31. Calculate XOR from 1 to n.
C#
PHP
<?php
// PHP program to find XOR
// of numbers from 1 to n.
// Function to calculate xor
function computeXOR($n)
{
184
Chapter 31. Calculate XOR from 1 to n.
Output :
185
Chapter 31. Calculate XOR from 1 to n.
10 1010 [1011]
11 1011 [0000] <------ We get 0
12 1100 [1100] <------ Equals to n
Source
https://www.geeksforgeeks.org/calculate-xor-1-n/
186
Chapter 32
Input: n = 5
Output: 25
Input: 7
Output: 49
Input: n = 12
Output: 144
187
Chapter 32. Calculate square of a number without using *, / and pow()
// Initialize result
int res = n;
// Add n to res n-1 times
for (int i=1; i<n; i++)
res += n;
return res;
}
// drive program
int main()
{
for (int n = 1; n<=5; n++)
cout << "n = " << n << ", n^2 = "
<< square(n) << endl;
return 0;
}
Java
188
Chapter 32. Calculate square of a number without using *, / and pow()
System.out.println("n = " + n +
", n^2 = " + square(n));
}
}
// This code is contributed by sunnysingh
Python3
# Simple solution to
# calculate square without
# using * and pow()
def square(n):
# handle negative input
if (n < 0):
n = -n
# Initialize result
res = n
# Add n to res n-1 times
for i in range(1, n):
res += n
return res
# Driver Code
for n in range(1, 6):
print("n =", n , end=", ")
print("n^2 =", square(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
189
Chapter 32. Calculate square of a number without using *, / and pow()
PHP
<?php
// PHP implementation to
// calculate square
// without using * and pow()
function square($n)
{
// handle negative input
if ($n < 0) $n = -$n;
// Initialize result
$res = $n;
// Add n to res n-1 times
for ($i = 1; $i < $n; $i++)
$res += $n;
return $res;
}
190
Chapter 32. Calculate square of a number without using *, / and pow()
// Drive Code
for ($n = 1; $n<=5; $n++)
echo "n = ", $n, ", ", "n^2 = ",
square($n), "\n ";
// This code is contributed by Ajit
?>
Output :
n = 1, n^2 = 1
n = 2, n^2 = 4
n = 3, n^2 = 9
n = 4, n^2 = 16
n = 5, n^2 = 25
Time complexity of above solution is O(n). We can do it in O(Logn) time using bitwise
operators. The idea is based on the following fact.
square(n) = 0 if n == 0
if n is even
square(n) = 4*square(n/2)
if n is odd
square(n) = 4*square(floor(n/2)) + 4*floor(n/2) + 1
Examples
square(6) = 4*square(3)
square(3) = 4*(square(1)) + 4*1 + 1 = 9
square(7) = 4*square(3) + 4*3 + 1 = 4*9 + 4*3 + 1 = 49
floor(n/2) can be calculated using bitwise right shift operator. 2*x and 4*x can be calculated
Below is the implementation based on above idea.
C++
191
Chapter 32. Calculate square of a number without using *, / and pow()
Java
192
Chapter 32. Calculate square of a number without using *, / and pow()
Python3
193
Chapter 32. Calculate square of a number without using *, / and pow()
# If n is even
else:
return (square(x) << 2);
# Driver Code
for n in range (1, 6):
print("n = " , n ," n^2 = ",
square(n))
# This code is contributed by Sam007
C#
194
Chapter 32. Calculate square of a number without using *, / and pow()
}
}
// This code is contributed by Sam0007.
PHP
<?php
// Square of a number using
// bitwise operators
function square($n)
{
// Base case
if ($n==0) return 0;
// Handle negative number
if ($n < 0) $n = -$n;
// Get floor(n/2)
// using right shift
$x = $n >> 1;
// If n is odd
if ($n & 1)
return ((square($x) << 2) +
($x << 2) + 1);
else // If n is even
return (square($x) << 2);
}
// Driver Code
for ($n = 1; $n <= 5; $n++)
echo "n = ", $n, ", n^2 = ", square($n),"\n";
// This code is contributed by ajit
?>
Output :
n = 1, n^2 = 1
n = 2, n^2 = 4
n = 3, n^2 = 9
n = 4, n^2 = 16
n = 5, n^2 = 25
195
Chapter 32. Calculate square of a number without using *, / and pow()
Source
https://www.geeksforgeeks.org/calculate-square-of-a-number-without-using-and-pow/
196
Chapter 33
Examples:
Approach:
197
Chapter 33. Calculate the total fine to be collected
C++
Java
// Java implementation to calculate
// the total fine collected
class GFG
{
198
Chapter 33. Calculate the total fine to be collected
// function to calculate
// the total fine collected
static int totFine(int car_num[], int n,
int date, int fine)
{
int tot_fine = 0;
// traverse the array elements
for (int i = 0; i < n; i++) // if both car no and date // are odd or both are even, //
then statement evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine;
// required total fine return tot_fine; } // Driver Code public static void main(String[]
args) { int car_num[] = { 3, 4, 1, 2 }; int n = car_num.length; int date = 15, fine = 250;
System.out.println(totFine(car_num, n, date, fine)); } } // This code is contributed // by
ChitraNayal [tabby title = ”Python 3”]
C#
199
Chapter 33. Calculate the total fine to be collected
// C# implementation to calculate
// the total fine collected
using System;
class GFG
{
// function to calculate the
// total fine collected
static int totFine(int[] car_num, int n,
int date, int fine)
{
int tot_fine = 0;
// traverse the array elements
for (int i = 0; i < n; i++) // if both car no and date // are odd or both are even, // then
statement evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required
total fine return tot_fine; } // Driver Code public static void Main() { int[] car_num = { 3, 4,
1, 2 }; int n = car_num.Length; int date = 15, fine = 250; Console.Write(totFine(car_num,
n, date, fine)); } } // This code is contributed // by ChitraNayal [tabby title=”PHP”]
Output:
500
Source:https://www.geeksforgeeks.org/microsoft-interview-experience-for-internship/
Improved By : ANKITRAI1, ChitraNayal
Source
https://www.geeksforgeeks.org/calculate-the-total-fine-to-be-collected/
200
Chapter 34
Case conversion (Lower to Upper and Vice Versa) of a string using BitWise operators in
C/C++ - GeeksforGeeks
Given a string, write a function that converts it either from lower to upper case or from upper
to lower case using the bitwise operators &(AND), |(OR), ~(NOT) in place and returns the
string.
Many of us know that Bitwise manipulations are faster than performing arithmetic opera-
tions for a compiler as the data is stored in binary form 0’s and 1’s.
Examples:
Input : "LowerToUpPer"
Output : "LOWERTOUPPER"
Letters already in the uppercase remains the same.
while rest get converted to uppercase.
Input : "UPPerTOloweR"
Output : "uppertolower"
Letters already in the lowercase remains the same.
while rest get converted to lowercase.
201
Chapter 34. Case conversion (Lower to Upper and Vice Versa) of a string using BitWise
operators in C/C++
Output:
SANJAYKANNA
202
Chapter 34. Case conversion (Lower to Upper and Vice Versa) of a string using BitWise
operators in C/C++
Output:
sanjaykanna
Explanation:
TheASCII table is constructed in such way that the binary representation of lowercase letters
is almost identical of binary representation of uppercase letters.
Character ‘A’ is integer 65 = (0100 0001)2, while character ‘a’ is integer 97 = (0110 0001)2.
The difference between the ASCII values of ‘a’ and ‘A’ is 32.
So we can easily change the case of the letters either from Upper to lower or lower to upper
by adding or subtracting the difference from the letters using bitwise operators as shown
above.
Exercise:
Implement a function that change the case of a string such that GeeksFoRgeekS turns
gEEKSfOrGEEKs .
Source
https://www.geeksforgeeks.org/case-conversion-lower-upper-vice-versa-string-using-bitwise-operators-cc/
203
Chapter 35
Input : 30
Output : 10
Binary representation of 11110.
Bits at Even positions are highlighted.
After making all of them 0, we get 01010
Input : 10
Output : 10
C++
204
Chapter 35. Change all even bits in a number to 0
int changeEvenBits(int n)
{
// To store sum of bits
// at even positions.
int to_subtract = 0;
// To store bits to shift
int m = 0;
// One by one put all even
// bits to end
for (int x = n; x; x >>= 2)
{
// If current last bit
// is set, add it to ans
if (x & 1)
to_subtract += (1 << m);
// Next shift position
m += 2;
}
return n - to_subtract;
}
// Driver code
int main()
{
int n = 30;
cout << changeEvenBits(n) << endl;
return 0;
}
Java
205
Chapter 35. Change all even bits in a number to 0
// To store bits to shift
int m = 0;
// One by one put all even
// bits to end
for (int x = n; x>0; x >>= 2)
{
// If current last bit
// is set, add it to ans
if ((x & 1) > 0)
to_subtract += (1 << m);
// Next shift position
m += 2;
}
return n - to_subtract;
}
// Driver code
public static void main(String[] args)
{
int n = 30;
System.out.println(changeEvenBits(n));
}
}
/* This code is contributed by Mr. Somesh Awasthi */
Python
206
Chapter 35. Change all even bits in a number to 0
while(x):
# If current last bit
# is set, add it to ans
if (x & 1):
to_subtract += (1 << m)
# Next shift position
m += 2
x >>= 2
return n - to_subtract
# Driver code
n = 30
print changeEvenBits(n)
# This code is contributed by Sachin Bisht
C#
207
Chapter 35. Change all even bits in a number to 0
// Next shift position
m += 2;
}
return n - to_subtract;
}
// Driver code
public static void Main()
{
int n = 30;
Console.Write(changeEvenBits(n));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to change even
// bits to 0.
// Returns modified number with
// all even bits 0.
function changeEvenBits($n)
{
// To store sum of bits
// at even positions.
$to_subtract = 0;
// To store bits to shift
$m = 0;
// One by one put all even
// bits to end
for ($x = $n; $x; $x >>= 2)
{
// If current last bit
// is set, add it to ans
if ($x & 1)
$to_subtract += (1 << $m);
// Next shift position
208
Chapter 35. Change all even bits in a number to 0
$m += 2;
}
return $n - $to_subtract;
}
// Driver code
$n = 30;
echo changeEvenBits($n) ;
// This code is contributed by nitin mittal
?>
Output :
10
Method 2 (Bitmask)
C++
#include<bits/stdc++.h>
using namespace std;
int convertEvenBitToOne(int n) {
return (n & 0xaaaaaaaa);
}
int main() {
int n = 30;
cout << convertEvenBitToOne(n);
return 0;
}
Java
209
Chapter 35. Change all even bits in a number to 0
{
return (n & 0xaaaaaaaa);
}
// Driver code
public static void main (String[] args)
{
int n = 30;
System.out.println(
convertEvenBitToOne(n));
}
}
// This code is contributed by anuj_67.
Python
def convertEvenBitToOne(n):
return (n & 0xaaaaaaaa)
# Driver code
n = 30
print convertEvenBitToOne(n)
# This code is contributed by Sachin Bisht
C#
210
Chapter 35. Change all even bits in a number to 0
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program using Bitmask to
// Change all even bits in a
// number to 0
function convertEvenBitToOne($n)
{
return ($n & 0xaaaaaaaa);
}
// Driver Code
$n = 30;
echo convertEvenBitToOne($n);
// This code is contributed by anuj_67.
?>
Output :
10
Source
https://www.geeksforgeeks.org/change-even-bits-number-0/
211
Chapter 36
Input : A = 175,
B = 66,
T = 100,
K = 5
Output : A = 36
B = 64
Initial bits of A = 1010 1111
Changed bits of A = 0010 0100
Initial bits of B = 0100 0010
Changed bits of B = 0100 0000
OR of changed Bits = 0110 0100
Which has decimal value equal to Target T.
Input : A = 175,
B = 66,
T = 100,
K = 4
Output : Not Possible
It is not possible to get OR of
A and B as T, just by changing K bits.
212
Chapter 36. Change bits to make specific OR value
We can solve this problem by iterating over all bits of A and B and greedily changing them
that is,
• If i-th bit of Target T is 0 then set i-th bits of A and B to 0 (if not already)
• If i-th bit of Target T is 1 then we will try to set one of the bits to 1 and we will
change i-th bit of B only to 1(if not already) to minimize A.
After above procedure, if changed bits are more than K, then it is not possible to get
OR of A and B as T by changing at most K bits.
If changed bits are less than k, then we can further minimize the value of A by using
remaining value of K for which we will loop over bits one more time and if at any time,
• i-th A bit is 1 and i-th B bit is 0 then we will make 2 changes and flip both.
• i-th A and B bits are 1 then again we will make 1 change and flip A’s bit.
213
Chapter 36. Change bits to make specific OR value
}
// Utility method to toggle bit at
// 'pos' position
void toggle(int &num,int pos)
{
num ^= (1 << pos);
}
// method returns minimum number of bit flip
// to get T as OR value of A and B
void minChangeToReachTaregetOR(int A, int B,
int K, int T)
{
int maxlen = max(bitCount(A), bitCount(B),
bitCount(T));
// Loop over maximum number of bits among
// A, B and T
for (int i = maxlen - 1; i >= 0; i--)
{
bool bitA = at_position(A, i);
bool bitB = at_position(B, i);
bool bitT = at_position(T, i);
// T's bit is set, try to toggle bit
// of B, if not already
if (bitT)
{
if (!bitA && !bitB)
{
toggle(B, i);
K--;
}
}
else
{
// if A's bit is set, flip that
if (bitA)
{
toggle(A, i);
K--;
}
// if B's bit is set, flip that
if (bitB)
{
toggle(B, i);
214
Chapter 36. Change bits to make specific OR value
K--;
}
}
}
// if K is less than 0 then we can make A|B == T
if (K < 0)
{
cout << "Not possible\n";
return;
}
// Loop over bits one more time to minimise
// A further
for (int i = maxlen - 1; K > 0 && i >= 0; --i)
{
bool bitA = at_position(A, i);
bool bitB = at_position(B, i);
bool bitT = at_position(T, i);
if (bitT)
{
// If both bit are set, then Unset
// A's bit to minimise it
if (bitA && bitB)
{
toggle(A, i);
K--;
}
}
// If A's bit is 1 and B's bit is 0,
// toggle both
if (bitA && !bitB && K >= 2)
{
toggle(A, i);
toggle(B, i);
K -= 2;
}
}
// Output changed value of A and B
cout << A << " " << B << endl;
}
// Driver code
int main()
{
215
Chapter 36. Change bits to make specific OR value
PHP
<?php
// PHP program to change least
// bits to get desired OR value
// Returns max of three numbers
function maxDD($a, $b, $c)
{
return max($a, (max($b, $c)));
}
// Returns count of bits in N
function bitCount($N)
{
$cnt = 0;
while ($N)
{
$cnt++;
$N >>= 1;
}
return $cnt;
}
// Returns bit at 'pos' position
function at_position($num, $pos)
{
$bit = $num & (1 << $pos);
return $bit;
}
// Utility method to toggle
// bit at 'pos' position
function toggle(&$num, $pos)
{
$num ^= (1 << $pos);
}
// method returns minimum
// number of bit flip to
// get T as OR value of A and B
function minChangeToReachTaregetOR($A, $B,
$K, $T)
216
Chapter 36. Change bits to make specific OR value
{
$maxlen = max(bitCount($A),
bitCount($B),
bitCount($T));
// Loop over maximum number
// of bits among A, B and T
for ( $i = $maxlen - 1; $i >= 0; $i--)
{
$bitA = at_position($A, $i);
$bitB = at_position($B, $i);
$bitT = at_position($T, $i);
// T's bit is set, try to toggle
// bit of B, if not already
if ($bitT)
{
if (!$bitA && !$bitB)
{
toggle($B, $i);
$K--;
}
}
else
{
// if A's bit is set,
// flip that
if ($bitA)
{
toggle($A, $i);
$K--;
}
// if B's bit is set,
// flip that
if ($bitB)
{
toggle($B, $i);
$K--;
}
}
}
// if K is less than 0 then
// we can make A|B == T
if ($K < 0)
{
echo "Not possible\n";
217
Chapter 36. Change bits to make specific OR value
return;
}
// Loop over bits one more
// time to minimise A further
for ($i = $maxlen - 1;
$K > 0 && $i >= 0; --$i)
{
$bitA = at_position($A, $i);
$bitB = at_position($B, $i);
$bitT = at_position($T, $i);
if ($bitT)
{
// If both bit are set, then
// Unset A's bit to minimise it
if ($bitA && $bitB)
{
toggle($A, $i);
$K--;
}
}
// If A's bit is 1 and B's
// bit is 0, toggle both
if ($bitA && !$bitB && $K >= 2)
{
toggle($A, $i);
toggle($B, $i);
$K -= 2;
}
}
// Output changed value
// of A and B
echo $A , " " , $B , "\n";
}
// Driver Code
$A = 175;
$B = 66;
$K = 5;
$T = 100;
minChangeToReachTaregetOR($A, $B, $K, $T);
// This code is contributed by ajit
?>
218
Chapter 36. Change bits to make specific OR value
Output :
36 64
Improved By : jit_t
Source
https://www.geeksforgeeks.org/change-bits-make-specific-value/
219
Chapter 37
Input: n = 11
Output: Odd
Input: n = 10
Output: Even
C++
220
Chapter 37. Check a number is odd or even without modulus operator
Java
221
Chapter 37. Check a number is odd or even without modulus operator
Python3
C#
222
Chapter 37. Check a number is odd or even without modulus operator
PHP
<?php
// A simple PHP program to check for
// even or odd
// Returns true if n is even,
// else odd
function isEven($n)
{
$isEven = true;
for ($i = 1; $i <= $n; $i++)
$isEven = !$isEven;
return $isEven;
}
// Driver code
$n = 101;
$is=isEven($n) ? "Even" : "Odd";
echo "$is"
// This code is contributed by ajit
?>
Output:
Odd
Method 2: By multiply and divide by 2. Divide the number by 2 and multiply by 2 if the
result is same as input then it is an even number else it is an odd number.
C++
223
Chapter 37. Check a number is odd or even without modulus operator
Java
224
Chapter 37. Check a number is odd or even without modulus operator
}
// This code is contributed by
// Smitha Dinesh Semwal.
Python 3
C#
// A simple C# program
// to check for even or odd
using System;
class GFG {
// Returns true if n
// is even, else odd
static bool isEven(int n)
{
// Return true if
// n/2 does not result
// in a float value.
return ((n / 2) * 2 == n);
225
Chapter 37. Check a number is odd or even without modulus operator
}
// Driver code
public static void Main(String[] args)
{
int n = 101;
if(isEven(n) != false)
Console.Write("Even");
else
Console.Write("Odd");
}
}
// This code is contributed by
// Smitha Dinesh Semwal.
PHP
<?php
// A simple PHP program to
// check for even or odd
// Returns true if n
// is even, else odd
function isEven($n)
{
// Return true if n/2
// does not result
// in a float value.
return ((int)($n / 2) * 2 == $n);
}
// Driver code
$n = 101;
if(isEven($n))
echo ("Even");
else
echo ("Odd");
// This code is contributed by
// Manish Shaw (manishshaw1)
?>
Output :
226
Chapter 37. Check a number is odd or even without modulus operator
Odd
input : 5 // odd
00000101
& 00000001
--------------
00000001
--------------
input : 8 //even
00001000
& 00000001
--------------
00000000
--------------
C++
Java
227
Chapter 37. Check a number is odd or even without modulus operator
Python3
228
Chapter 37. Check a number is odd or even without modulus operator
print ("Odd");
# This code is contributed
# by Manish Shaw (manishshaw1)
C#
PHP
<?php
// A simple PHP program to
// check for even or odd
// Returns 0 if n
// is even, else odd
function isEven($n)
{
229
Chapter 37. Check a number is odd or even without modulus operator
// n&1 is 1, then
// odd, else even
return ($n & 1);
}
// Driver code
$n = 101;
if(isEven($n) == 0)
echo ("Even");
else
echo ("Odd");
// This code is contributed
// by Manish Shaw (manishshaw1)
?>
Output :
Odd
Source
https://www.geeksforgeeks.org/3-ways-check-number-odd-even-without-using-modulus-operator-set-2-can-merge-h
230
Chapter 38
231
Chapter 38. Check divisibility in a binary stream
Problem in this solution: What about the overflow. Since 0 and 1 will keep on coming and
the number formed will go out of range of integer.
232
Chapter 38. Check divisibility in a binary stream
233
Chapter 38. Check divisibility in a binary stream
return 0;
}
Input:
1
0
1
0
1
-1
Output:
Related Articles:
DFA based division
Check if a stream is Multiple of 3
Source
https://www.geeksforgeeks.org/check-divisibility-binary-stream/
234
Chapter 39
Input : 11000 k = 2
Output : Yes
Explanation :
(11000)2 = (24)10
24 is evenly divisible by 2k i.e. 4.
Input : 10101 k = 3
Output : No
Explanation :
(10101)2 = (21)10
21 is not evenly divisible by 2k i.e. 8.
Naive Approach : Compute the binary string into decimal and then simply check whether
it is divisible by 2k . But, this approach is not feasible for long binary string as time
complexity will be high for computing decimal number from binary string and then dividing
it by 2k .
Efficient Approach : In the binary string, check for last k bits. If the all the last k bits
are 0, then the binary number is evenly divisible by 2k else it is not evenly divisible. Time
complexity using this approach is O(k).
Below is the implementation of the approach.
C++
235
Chapter 39. Check divisibility of binary string by 2^k
236
Chapter 39. Check divisibility of binary string by 2^k
Java
237
Chapter 39. Check divisibility of binary string by 2^k
Python 3
C#
238
Chapter 39. Check divisibility of binary string by 2^k
239
Chapter 39. Check divisibility of binary string by 2^k
// This code is contributed by Smitha.
PHP
<?php
// PHP implementation to check whether
// given binary number is evenly
// function to check whether
// given binary number is
// evenly divisible by 2^k or not
function isDivisible($str, $k)
{
$n = strlen($str);
$c = 0;
// count of number
// of 0 from last
for ($i = 0; $i < $k; $i++)
if ($str[$n - $i - 1] == '0')
$c++;
// if count = k,
// number is evenly
// divisible, so
// returns true else
// false
return ($c == $k);
}
// Driver Code
// first example
$str1 = "10101100";
$k = 2;
if (isDivisible($str1, $k))
echo "Yes", "\n";
else
echo "No", "\n";
// Second example
$str2= "111010100";
$k = 2;
if (isDivisible($str2, $k))
echo "Yes", "\n";
else
echo "No", "\n";
240
Chapter 39. Check divisibility of binary string by 2^k
Output:
Yes
Yes
Source
https://www.geeksforgeeks.org/check-divisibility-binary-string-2k/
241
Chapter 40
1) Calculate sum
2) If both numbers are positive and sum is negative then return -1
Else
If both numbers are negative and sum is positive then return -1
Else return 0
#include<stdio.h>
#include<stdlib.h>
/* Takes pointer to result and two numbers as
arguments. If there is no overflow, the function
places the resultant = sum a+b in “result” and
returns 0, otherwise it returns -1 */
int addOvf(int* result, int a, int b)
{
*result = a + b;
if(a > 0 && b > 0 && *result < 0)
return -1;
if(a < 0 && b < 0 && *result > 0)
return -1;
return 0;
242
Chapter 40. Check for Integer Overflow
}
int main()
{
int *res = (int *)malloc(sizeof(int));
int x = 2147483640;
int y = 10;
printf("%d", addOvf(res, x, y));
printf("\n %d", *res);
getchar();
return 0;
}
#include<stdio.h>
#include<limits.h>
#include<stdlib.h>
int addOvf(int* result, int a, int b)
{
if( a > INT_MAX - b)
return -1;
else
{
*result = a + b;
return 0;
}
}
int main()
{
int *res = (int *)malloc(sizeof(int));
int x = 2147483640;
int y = 10;
printf("%d", addOvf(res, x, y));
printf("\n %d", *res);
getchar();
return 0;
}
243
Chapter 40. Check for Integer Overflow
Source
https://www.geeksforgeeks.org/check-for-integer-overflow/
244
Chapter 41
Input: x = 72
Output: true
Explanation: Binary representation of 72 is 01001000.
There are no two consecutive 1's in binary representation
Input: x = 12
Output: false
Explanation: Binary representation of 12 is 1100.
Third and fourth bits (from end) are set.
If we observer carefully, then we can notice that if we can use bitwise AND of binary
representation of the “given number its “right shifted number”(i.e., half the given number)
to figure out whether the number is sparse or not. Result of AND operator would be 0 if
number is sparse and non-zero if not sparse.
245
Chapter 41. Check if a given number is sparse or not
C++
Java
246
Chapter 41. Check if a given number is sparse or not
Python3
247
Chapter 41. Check if a given number is sparse or not
print(checkSparse(12))
print(checkSparse(2))
print(checkSparse(30))
# This code is contributed
# by Anant Agarwal.
C#
PHP
<?php
// PHP program to check if
// n is sparse or not
// Return true if n is sparse,
// else false
248
Chapter 41. Check if a given number is sparse or not
function checkSparse($n)
{
// n is not sparse if
// there is set in AND
// of n and n/2
if ($n & ($n >> 1))
return 0;
return 1;
}
// Driver Code
echo checkSparse(72), "\n";
echo checkSparse(12), "\n";
echo checkSparse(2), "\n";
echo checkSparse(3), "\n";
// This code is contributed by Ajit.
?>
Output :
1
0
1
0
Note: Instead of right shift, we could have used left shift also, but left shift might lead to
overflow in some cases.
This article is contributed by Vimal Vestron. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007, jit_t
Source
https://www.geeksforgeeks.org/check-if-a-given-number-is-sparse-or-not/
249
Chapter 42
Input : 24
Output : Yes
Explanation: 24 can be expressed as
24 + 23
Input : 13
output : No
Explanation: It is not possible to
express 13 as sum of two powers of 2.
If we take few examples, we can notice that a number can be expressed in the form of 2^x
+ 2^y if the number is already a power of 2 ( for n > 1 ) or the remainder we get after
subtracting previous power of two from the number is also a power of 2.
Below is the implementation of above idea
C++
250
Chapter 42. Check if a number can be expressed as 2^x + 2^y
251
Chapter 42. Check if a number can be expressed as 2^x + 2^y
return false;
}
// driver code
int main()
{
int n1 = 20;
if (checkSum(n1) == false)
cout << "No";
cout << endl;
int n2 = 11;
if (checkSum(n2) == false)
cout << "No";
return 0;
}
Java
252
Chapter 42. Check if a number can be expressed as 2^x + 2^y
// if value of n is 0 or 1
// it can not be expressed as
// 2^x + 2^y
if (n == 0 || n == 1)
return false;
// if a number is power of 2
// it can be expressed as
// 2^x + 2^y
else if (isPowerOfTwo(n)) {
System.out.println(n / 2 + " " + n / 2);
}
else {
// if the remainder after
// subtracting previous power of 2
// is also a power of 2 then
// it can be expressed as
// 2^x + 2^y
int x = previousPowerOfTwo(n);
int y = n - x;
if (isPowerOfTwo(y)) {
System.out.println(x + " " + y);
return true;
}
}
return false;
}
// driver code
public static void main(String[] argc)
{
int n1 = 20;
if (checkSum(n1) == false)
System.out.println("No");
System.out.println();
int n2 = 11;
if (checkSum(n2) == false)
System.out.println("No");
}
}
Python3
253
Chapter 42. Check if a number can be expressed as 2^x + 2^y
254
Chapter 42. Check if a number can be expressed as 2^x + 2^y
# driver code
n1 = 20
if (checkSum(n1)):
print("No")
n2 = 11
if (checkSum(n2)):
print("No")
C#
255
Chapter 42. Check if a number can be expressed as 2^x + 2^y
// if a number is power of
// it can be expressed as
// 2^x + 2^y
else if (isPowerOfTwo(n)) {
Console.WriteLine(n / 2 + " " + n / 2);
return true;
}
else {
// if the remainder after
// subtracting previous power of 2
// is also a power of 2 then
// it can be expressed as
// 2^x + 2^y
int x = previousPowerOfTwo(n);
int y = n - x;
if (isPowerOfTwo(y)) {
Console.WriteLine(x + " " + y);
return true;
}
else {
return false;
}
}
}
// driver code
public static void Main()
{
int n1 = 20;
if (checkSum(n1) == false)
Console.WriteLine("No");
Console.WriteLine();
int n2 = 11;
if (checkSum(n2) == false)
Console.WriteLine("No");
}
}
PHP
<?php
// PHP code to check if a number
// can be expressed as 2^x + 2^y
256
Chapter 42. Check if a number can be expressed as 2^x + 2^y
// Utility function to check if
// a number is power of 2 or not
function isPowerOfTwo($n)
{
return ($n and !($n & ($n - 1)));
}
// Utility function to determine
// the value of previous power of 2
function previousPowerOfTwo($n)
{
while ($n & $n - 1)
{
$n = $n & $n - 1;
}
return $n;
}
// function to check if
// n can be expressed
// as 2^x + 2^y or not
function checkSum($n)
{
// if value of n is 0 or 1
// it can not be expressed
// as 2^x + 2^y
if ($n == 0 or $n == 1)
return false;
// if a number is power of 2
// then it can be expressed
// as 2^x + 2^y
else if (isPowerOfTwo($n))
{
echo " " , $n / 2 , " " , $n / 2;
return true;
}
else
{
// if the remainder after
// subtracting previous power
// of 2 is also a power of 2
// then it can be expressed
// as 2^x + 2^y
$x = previousPowerOfTwo($n);
$y = $n - $x;
257
Chapter 42. Check if a number can be expressed as 2^x + 2^y
if (isPowerOfTwo($y))
{
echo $x, " ", $y;
return true;
}
}
return false;
}
// Driver code
$n1 = 20;
if (checkSum($n1) == false)
echo "No";
echo"\n";
$n2 = 11;
if (checkSum($n2) == false)
echo "No";
// This code is contributed
// by chandan_jnu.
?>
Output:
16 4
No
Improved By : Chandan_Kumar
Source
https://www.geeksforgeeks.org/check-if-a-number-can-be-expressed-as-2x-2y/
258
Chapter 43
Input : n = 10
Output : true
It can be expressed as sum of two consecutive
numbers 1 + 2 + 3 + 4.
Input : n = 16
Output : false
It cannot be expressed as sum of two consecutive
numbers.
Input : n = 5
Output : true
2 + 3 = 5
There is a direct and quick method to solve this. If a number is a power of two, then it
cannot be expressed as a sum of consecutive numbers otherwise Yes.
The idea is based on below two facts.
1) Sum of any two consecutive numbers is odd as one of them has to be even and other odd.
2) 2n = 2n-1 + 2n-1
259
Chapter 43. Check if a number can be expressed as a sum of consecutive numbers
If we take a closer look at 1) and 2), we can get intuition behind the fact.
Below is implementation of above idea.
C++
Java
260
Chapter 43. Check if a number can be expressed as a sum of consecutive numbers
{
int n = 15;
System.out.println(canBeSumofConsec(n) ? "true" : "false");
}
}
Python3
C#
261
Chapter 43. Check if a number can be expressed as a sum of consecutive numbers
PHP
<?php
// php program to check if a number
// can be expressed as sum of
// consecutive numbers
// This function returns true if n
// can be expressed sum of consecutive.
function canBeSumofConsec($n)
{
// We basically return true if n is a
// power of two
return (($n & ($n - 1)) && $n);
}
// Driver code
$n = 15;
if(canBeSumofConsec($n))
echo "true" ;
else
echo "false";
// This code is contributed by
// nitin mittal.
?>
Output:
True
Reference:
http://www.cut-the-knot.org/arithmetic/UnpropertyOfPowersOf2.shtml
Improved By : nitin mittal
262
Chapter 43. Check if a number can be expressed as a sum of consecutive numbers
Source
https://www.geeksforgeeks.org/check-number-can-expressed-sum-consecutive-numbers/
263
Chapter 44
Input : 15
Output : No
Explanation: Binary representation of 15 is 1111.
Input : 10
Output : Yes
Explanation: Binary representation of 10 is 1010.
A simple approach is to find its binary equivalent and then check its bits.
C++
264
Chapter 44. Check if a number has bits in alternate pattern | Set 1
bool findPattern(int n)
{
// Store last bit
int prev = n % 2;
n = n/2;
// Traverse through remaining bits
while (n > 0)
{
int curr = n % 2;
// If current bit is same as previous
if (curr == prev)
return false;
prev = curr;
n = n / 2;
}
return true;
}
// Driver code
int main()
{
int n = 10;
if (findPattern(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
265
Chapter 44. Check if a number has bits in alternate pattern | Set 1
// Traverse through remaining bits
while (n > 0)
{
int curr = n % 2;
// If current bit is same as previous
if (curr == prev)
return false;
prev = curr;
n = n / 2;
}
return true;
}
// Driver method
public static void main(String args[])
{
int n = 10;
System.out.println(findPattern(n) ? "Yes" : "No");
}
}
Python3
266
Chapter 44. Check if a number has bits in alternate pattern | Set 1
prev = curr
n = n // 2
return True
# Driver code
n = 10
print("Yes") if(findPattern(n)) else print("No")
# This code is contributed by Anant Agarwal.
C#
267
Chapter 44. Check if a number has bits in alternate pattern | Set 1
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to find if a
// number has alternate
// bit pattern
// Returns true if n has
// alternate bit pattern
// else false
function findPattern($n)
{
// Store last bit
$prev = $n % 2;
$n = $n / 2;
// Traverse through
// remaining bits
while ($n > 0)
{
$curr = $n % 2;
// If current bit is
// same as previous
if ($curr == $prev)
return false;
$prev = $curr;
$n = floor($n / 2);
}
return true;
}
// Driver code
$n = 10;
if (findPattern($n))
echo "Yes";
else
echo "No";
return 0;
268
Chapter 44. Check if a number has bits in alternate pattern | Set 1
Output:
Yes
Reference:
http://stackoverflow.com/questions/38690278/program-to-check-whether-the-given-integer-has-an-alternate-patter
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/check-if-a-number-has-bits-in-alternate-pattern/
269
Chapter 45
Check if a number has bits in alternate pattern | Set-2 O(1) Approach - GeeksforGeeks
Given a positive integer n. The problem is to check whether this integer has an alternate
pattern in its binary representation or not. Here alternate pattern means that the set and
unset bits in n occur in alternate order. For example- 5 has an alternate pattern i.e. 101.
Print “Yes” if it has an alternate pattern otherwise “No”.
Note: 0 < n.
Examples :
Input : 10
Output : Yes
(10)10 = (1010)2, has an alternate pattern.
Input : 12
Output : No
(12)10 = (1100)2, does not have an alternate pattern.
Simple Approach: It has been discussed in this post having a time complexity of O(n).
Efficient Approach: Following are the steps:
270
Chapter 45. Check if a number has bits in alternate pattern | Set-2 O(1) Approach
C++
Java
271
Chapter 45. Check if a number has bits in alternate pattern | Set-2 O(1) Approach
C#
// C# implementation to check if a
// number has bits in alternate pattern
using System;
class GFG {
272
Chapter 45. Check if a number has bits in alternate pattern | Set-2 O(1) Approach
PHP
<?php
// PHP implementation to check
// if a number has bits in
// alternate pattern
// function to check if all the
// bits are set or not in the
273
Chapter 45. Check if a number has bits in alternate pattern | Set-2 O(1) Approach
Output :
Yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-number-bits-alternate-pattern-set-2-o1-approach/
274
Chapter 46
Check if a number has same number of set and unset bits - GeeksforGeeks
Given a number N, the task is to check whether the count of the set and unset bits in the
given number are same.
Examples:
Input: 12
Output: Yes
1100 is the binary representation of 12
which has 2 set and 2 unset bits
Input: 14
Output: No
Approach: Traverse in the binary representation of the given number, check if the leftmost
bit is set or not using n & 1. If n & 1 returns 1, then the left most bit is set. Right, shift the
number every time by 1 to check the next bit. Once the binary representation is traversed
completely, check if the number of set bit and unset bits are same. If they are same, print
“YES” else print “NO”.
Below is the implementation of the above approach:
C++
275
Chapter 46. Check if a number has same number of set and unset bits
// Function to check if a number
// has same setbits and unset bits
bool checkSame(int n)
{
int set = 0, unset = 0;
// iterate for all bits of a number
while (n) {
// if set
if (n & 1)
set++;
// if unset
else
unset++;
// right shift number by 1
n = n >> 1;
}
// is number of set bits are
// equal to unset bits
if (set == unset)
return true;
else
return false;
}
// Driver Code
int main()
{
int n = 12;
// function to check
if (checkSame(n))
cout << "YES";
else
cout << "NO";
return 0;
}
Java
276
Chapter 46. Check if a number has same number of set and unset bits
class GFG
{
// Function to check if a
// number has same setbits
// and unset bits
static boolean checkSame(int n)
{
int set = 0;
int unset = 0;
// iterate for all
// bits of a number
while (n == 0)
{
// if set
if (n > 1)
set++;
// if unset
else
unset++;
// right shift
// number by 1
n = n >> 1;
}
// is number of set bits
// are equal to unset bits
if (set == unset)
return true;
else
return false;
}
// Driver Code
public static void main (String[] args)
{
int n = 12;
// function to check
if (checkSame(n))
System.out.println ("YES");
else
System.out.println("NO");
277
Chapter 46. Check if a number has same number of set and unset bits
}
}
// This code is contributed
// by akt_mit
Output:
YES
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-if-a-number-has-same-number-of-set-and-unset-bits/
278
Chapter 47
Input : N = 67
Output : Yes
There is a pair of adjacent set bit
The binary representation is 100011
Input : N = 5
Output : No
A simple solution is traverse all bits. For every set bit, check if next bit is also set.
An efficient solution is to shift number by 1 and then do bitwise AND. If bitwise AND is
non-zero then there are two adjacent set bits. Else not.
C++
279
Chapter 47. Check if a number has two adjacent set bits
Java
C#
280
Chapter 47. Check if a number has two adjacent set bits
// C# program to check
// if there are two
// adjacent set bits.
using System;
class GFG
{
static bool adjacentSet(int n)
{
int x = (n & (n >> 1));
if(x == 1)
return true;
else
return false;
}
// Driver code
public static void Main ()
{
int n = 3;
if(adjacentSet(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Sam007.
php
<?php
// PHP program to check
// if there are two
// adjacent set bits.
function adjacentSet($n)
{
return ($n & ($n >> 1));
}
// Driver Code
$n = 3;
adjacentSet($n) ?
print("Yes") :
281
Chapter 47. Check if a number has two adjacent set bits
print("No");
// This code is contributed by Sam007.
?>
Output :
Yes
Improved By : Sam007
Source
https://www.geeksforgeeks.org/check-number-two-adjacent-set-bits/
282
Chapter 48
Input : n = 3
Output : false
3 is not Bleak as it can be represented
as 2 + countSetBits(2).
Input : n = 4
Output : true
4 is t Bleak as it cannot be represented
as sum of a number x and countSetBits(x)
for any number x.
Method 1 (Simple)
bool isBleak(n)
1) Consider all numbers smaller than n
a) If x + countSetBits(x) == n
return false
2) Return true
C++
283
Chapter 48. Check if a number is Bleak
Java
284
Chapter 48. Check if a number is Bleak
int count = 0;
while (x != 0) {
x &= (x - 1);
count++;
}
return count;
}
// Returns true if n is Bleak
static boolean isBleak(int n)
{
// Check for all numbers 'x' smaller
// than n. If x + countSetBits(x)
// becomes n, then n can't be Bleak
for (int x = 1; x < n; x++)
if (x + countSetBits(x) == n)
return false;
return true;
}
// Driver code
public static void main(String args[])
{
if (isBleak(3))
System.out.println("Yes");
else
System.out.println("No");
if (isBleak(4))
System.out.println("Yes");
else
System.out.println("No");
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3
285
Chapter 48. Check if a number is Bleak
count = 0
while (x) :
x = x & (x-1)
count = count + 1
return count
# Returns true if n
# is Bleak
def isBleak(n) :
# Check for all numbers 'x'
# smaller than n. If x +
# countSetBits(x) becomes
# n, then n can't be Bleak.
for x in range(1, n) :
if (x + countSetBits(x) == n) :
return False
return True
# Driver code
if(isBleak(3)) :
print( "Yes")
else :
print("No")
if(isBleak(4)) :
print("Yes")
else :
print( "No")
# This code is contributed by Nikita Tiwari.
C#
286
Chapter 48. Check if a number is Bleak
{
int count = 0;
while (x != 0) {
x &= (x - 1);
count++;
}
return count;
}
// Returns true if n is Bleak
static bool isBleak(int n)
{
// Check for all numbers
// 'x' smaller than n. If
// x + countSetBits(x)
// becomes n, then n can't
// be Bleak
for (int x = 1; x < n; x++)
if (x + countSetBits(x)
== n)
return false;
return true;
}
// Driver code
public static void Main()
{
if (isBleak(3))
Console.Write("Yes");
else
Console.WriteLine("No");
if (isBleak(4))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by
// Nitin mittal
PHP
287
Chapter 48. Check if a number is Bleak
<?php
// A simple PHP program
// to check Bleak Number
// Function to get no of
// set bits in binary
// representation of
// passed binary no.
function countSetBits( $x)
{
$count = 0;
while ($x)
{
$x &= ($x - 1);
$count++;
}
return $count;
}
// Returns true if n is Bleak
function isBleak( $n)
{
// Check for all numbers 'x' smaller
// than n. If x + countSetBits(x)
// becomes n, then n can't be Bleak
for($x = 1; $x < $n; $x++)
if ($x + countSetBits($x) == $n)
return false;
return true;
}
// Driver code
if(isBleak(3))
echo "Yes\n" ;
else
echo "No\n";
if(isBleak(4))
echo "Yes\n" ;
else
echo "No\n";
// This code is contributed by anuj_67.
?>
Output :
288
Chapter 48. Check if a number is Bleak
No
Yes
Method 2 (Efficient)
The idea is based on the fact that the largest count of set bits in any number smaller
than n cannot exceed ceiling of Log2 n. So we need to check only numbers from range n –
ceilingLog2(n) to n.
bool isBleak(n)
1) Consider all numbers n - ceiling(Log2n) to n-1
a) If x + countSetBits(x) == n
return false
2) Return true
C++
289
Chapter 48. Check if a number is Bleak
while (x > 0) {
x = x >> 1;
count++;
}
return count;
}
// Returns true if n is Bleak
bool isBleak(int n)
{
// Check for all numbers 'x' smaller
// than n. If x + countSetBits(x)
// becomes n, then n can't be Bleak
for (int x = n - ceilLog2(n); x < n; x++)
if (x + countSetBits(x) == n)
return false;
return true;
}
// Driver code
int main()
{
isBleak(3) ? cout << "Yes\n" : cout << "No\n";
isBleak(4) ? cout << "Yes\n" : cout << "No\n";
return 0;
}
Java
290
Chapter 48. Check if a number is Bleak
// A function to return ceiling of log x
// in base 2. For example, it returns 3
// for 8 and 4 for 9.
static int ceilLog2(int x)
{
int count = 0;
x--;
while (x > 0) {
x = x >> 1;
count++;
}
return count;
}
// Returns true if n is Bleak
static boolean isBleak(int n)
{
// Check for all numbers 'x' smaller
// than n. If x + countSetBits(x)
// becomes n, then n can't be Bleak
for (int x = n - ceilLog2(n); x < n; x++)
if (x + countSetBits(x) == n)
return false;
return true;
}
// Driver code
public static void main(String[] args)
{
if (isBleak(3))
System.out.println("Yes");
else
System.out.println("No");
if (isBleak(4))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Prerna Saini
Python3
291
Chapter 48. Check if a number is Bleak
import math
# Function to get no of set
# bits in binary representation
# of passed binary no.
def countSetBits(x) :
count = 0
while (x) :
x = x & (x - 1)
count = count + 1
return count
# A function to return ceiling
# of log x in base 2. For
# example, it returns 3 for 8
# and 4 for 9.
def ceilLog2(x) :
count = 0
x = x - 1
while (x > 0) :
x = x>>1
count = count + 1
return count
# Returns true if n is Bleak
def isBleak(n) :
# Check for all numbers 'x'
# smaller than n. If x +
# countSetBits(x) becomes n,
# then n can't be Bleak
for x in range ((n - ceilLog2(n)), n) :
if (x + countSetBits(x) == n) :
return False
return True
# Driver code
if(isBleak(3)) :
print("Yes")
else :
292
Chapter 48. Check if a number is Bleak
print( "No")
if(isBleak(4)) :
print("Yes")
else :
print("No")
# This code is contributed by Nikita Tiwari.
C#
293
Chapter 48. Check if a number is Bleak
// Check for all numbers
// 'x' smaller than n. If
// x + countSetBits(x)
// becomes n, then n
// can't be Bleak
for (int x = n - ceilLog2(n);
x < n; x++)
if (x + countSetBits(x)
== n)
return false;
return true;
}
// Driver code
public static void Main()
{
if (isBleak(3))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
if (isBleak(4))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by anuj_67.
PHP
<?php
// An efficient PHP program
// to check Bleak Number
/* Function to get no of set
bits in binary representation
of passed binary no. */
function countSetBits( $x)
{
$count = 0;
while ($x)
{
$x &= ($x - 1);
$count++;
294
Chapter 48. Check if a number is Bleak
}
return $count;
}
// A function to return ceiling of log x
// in base 2. For example, it returns 3
// for 8 and 4 for 9.
function ceilLog2( $x)
{
$count = 0;
$x--;
while ($x > 0)
{
$x = $x >> 1;
$count++;
}
return $count;
}
// Returns true if n is Bleak
function isBleak( $n)
{
// Check for all numbers 'x' smaller
// than n. If x + countSetBits(x)
// becomes n, then n can't be Bleak
for ($x = $n - ceilLog2($n); $x < $n; $x++)
if ($x + countSetBits($x) == $n)
return false;
return true;
}
// Driver code
if(isBleak(3))
echo "Yes\n" ;
else
echo "No\n";
if(isBleak(4))
echo "Yes\n" ;
else
echo "No\n";
// This code is contributed by anuj_67
295
Chapter 48. Check if a number is Bleak
?>
Output :
No
Yes
Output :
1
4
This article is contributed by Rahuain. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/check-if-a-number-is-bleak/
296
Chapter 49
Input : n = 34
Output : 34 is divisible by 17
Input : n = 43
Output : 43 is not divisible by 17
n/17 = (16*n)/(17*16)
= (17 - 1)*n/(17*16)
= (n/16) - (n/(17*16))
297
Chapter 49. Check if a number is divisible by 17 using bitwise operators
The left-hand-side of this equation is n/17. That will be an integer only when the right-
hand-side is an integer. floor(n/16) is an integer by definition. So the whole left-hand-side
would be an integer if (floor(n/16)-n%16)/17 is also an integer.
This implies n is divisible by 17 if (floor(n/16)-n%16) is divisible by 17.
(floor(n/16)-n%16) can be written in bitwise as (int)(n>>4) – (int)(n&15) where
n>>4 means n/16 and n%15 means n%15
Below is the implementation of the above approach:
CPP
Java
298
Chapter 49. Check if a number is divisible by 17 using bitwise operators
Python3
# Python 3 program to
# check if a number is
# divisible by 17 or
# not using bitwise
# operator.
299
Chapter 49. Check if a number is divisible by 17 using bitwise operators
# function to check recursively if the
# number is divisible by 17 or not
def isDivisibleby17(n):
# if n=0 or n=17 then yes
if (n == 0 or n == 17):
return True
# if n is less then 17, not
# divisible by 17
if (n < 17):
return False
# reducing the number by floor(n/16)
# - n%16
return isDivisibleby17((int)(n >> 4) - (int)(n & 15))
# driver code to check the above function
n = 35
if (isDivisibleby17(n)):
print(n,"is divisible by 17")
else:
print(n,"is not divisible by 17")
# This code is contributed by
# Smitha Dinesh Semwal
C#
300
Chapter 49. Check if a number is divisible by 17 using bitwise operators
PHP
<?php
// php program to check if a
// number is divisible by 17
// or not using bitwise
// operator.
// function to check recursively
// if the number is divisible
// by 17 or not
function isDivisibleby17($n)
{
// if n=0 or n=17 then yes
if ($n == 0 || $n == 17)
return true;
// if n is less then 17, not
// divisible by 17
if ($n < 17)
301
Chapter 49. Check if a number is divisible by 17 using bitwise operators
return false;
// reducing the number by floor(n/16)
// - n%16
return isDivisibleby17((int)($n >> 4) -
(int)($n & 15));
}
// Driver Code
$n = 35;
if (isDivisibleby17($n))
echo $n." is divisible by 17";
else
echo $n." is not divisible by 17";
// This code is contributed by mits
?>
Output:
35 is not divisible by 17
Source
https://www.geeksforgeeks.org/check-number-divisible-17-using-bitwise-operators/
302
Chapter 50
Input : 16
Output :YES
Input :15
Output :NO
Approach: Result = (((n >> 3) << 3) == n). First we shift the 3 bit right then we shift
the 3 bit left and then compare the number with the given number if the number is equal
to the number then it is the divisible by 8 .
Explanation:
Example: n = 16 given so binary of the 16 is 10000 now we shift the 3 bit right, now we
have 00010 so again we shift the 3 bit left, then we have 10000 now compare with the given
number first 16==16 in binary so it true so the number is divisible by 8.
CPP
303
Chapter 50. Check if a number is divisible by 8 using bitwise operators
Java
304
Chapter 50. Check if a number is divisible by 8 using bitwise operators
Python3
C#
// C# program to check whether
// the number is divisible by
// 8 or not using bitwise operator
using System;
class GFG {
// function to check number is
// div by 8 or not using bitwise
// operator
static bool Div_by_8(int n)
{
return (((n >> 3) << 3) == n);
}
// Driver code
public static void Main ()
305
Chapter 50. Check if a number is divisible by 8 using bitwise operators
{
int n = 16;
if (Div_by_8(n))
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to check whether
// the number is divisible by
// 8 or not using bitwise operator
// function to check number is
// div by 8 or not using bitwise
// operator
function Div_by_8($n)
{
return ((($n >> 3) << 3) == $n);
}
// Driver program
$n = 16;
if (Div_by_8($n))
echo "YES";
else
echo "NO";
//This code is contributed by mits.
?>
YES
Source
https://www.geeksforgeeks.org/check-number-divisible-8-using-bitwise-operators/
306
Chapter 51
C++
307
Chapter 51. Check if a number is multiple of 9 using bitwise operators
// Driver program to test above function
int main()
{
// Let us print all multiples of 9 from 0 to 100
// using above method
for (int i = 0; i < 100; i++)
if (isDivBy9(i))
cout << i << " ";
return 0;
}
Java
308
Chapter 51. Check if a number is multiple of 9 using bitwise operators
Python3
C#
309
Chapter 51. Check if a number is multiple of 9 using bitwise operators
return false;
// If n is greater than 9, then
// recur for [floor(n/9) - n%8]
return isDivBy9((int)(n >> 3) - (int)(n & 7));
}
// Driver code
public static void Main()
{
// Let us print all multiples of 9 from
// 0 to 100 using above method
for (int i = 0; i < 100; i++)
if (isDivBy9(i))
Console.Write(i + " ");
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to check if a number
// is multiple of 9 using bitwise
// operators
// Bitwise operator based function
// to check divisibility by 9
function isDivBy9($n)
{
// Base cases
if ($n == 0 || $n == 9)
return true;
if ($n < 9)
return false;
// If n is greater than 9,
// then recur for [floor(n/9) -
// n%8]
return isDivBy9(($n >> 3) -
($n & 7));
}
// Driver Code
// Let us print all multiples
// of 9 from 0 to 100
310
Chapter 51. Check if a number is multiple of 9 using bitwise operators
Output:
0 9 18 27 36 45 54 63 72 81 90 99
Since we need to use bitwise operators, we get the value of floor(n/8) using n>>3 and get
value of n%8 using n&7. We need to write above expression in terms of floor(n/8) and n%8.
n/8 is equal to “floor(n/8) + (n%8)/8”. Let us write the above expression in terms of
floor(n/8) and n%8
Source
https://www.geeksforgeeks.org/divisibility-9-using-bitwise-operators/
311
Chapter 52
Input : 30
Output : 30 is positive
Input : -20
Output : -20 is negative
Input: 0
Output: 0 is zero
The signed shift n>>31 converts every negative number into -1 and every other into 0.
When we do a -n>>31, if it is a positive number then it will return -1 as we are doing
-n>>31 and the vice versa when we do for a negative number.
But when we do for 0 then n>>31 and -n>>31 both returns 0, so we get a formula:
1 + (n>>31) – (-n>>31)
312
Chapter 52. Check if a number is positive, negative or zero using bit operators
CPP
Java
313
Chapter 52. Check if a number is positive, negative or zero using bit operators
Python3
# Python 3 program to
# find if a number is
# positive, negative
# or zero using
# bit wise operators.
# function to return 1 if it is zero
314
Chapter 52. Check if a number is positive, negative or zero using bit operators
# returns 0 if it is negative
# returns 2 if it is positive
def index(i):
return 1 + (i >> 31) - (-i >> 31)
def check(n):
# string array to store all kinds of number
s = "negative", "zero", "positive"
# function call to check the sign of number
val = index(n)
print(n,"is",s[val])
# driver program to
# test the above function
check(30)
check(-20)
check(0)
# This code is contributed by
# Smitha Dinesh Semwal
C#
315
Chapter 52. Check if a number is positive, negative or zero using bit operators
PHP
<?php
// PHP program to find if a number is
// positive, negative or zero using
// bit wise operators.
// function to return 1 if it is zero
// returns 0 if it is negative
// returns 2 if it is positive
function index($i)
{
return 1 + ($i >> 31) -
(-$i >> 31);
}
function check($n)
{
// string array to store
// all kinds of number
$s = array("negative", "zero", "positive" );
// function call to check
// the sign of number
$val = index($n);
echo $n, " is ", $s[$val], "\n";
}
316
Chapter 52. Check if a number is positive, negative or zero using bit operators
// Driver Code
check(30);
check(-20);
check(0);
// This code is contributed by Ajit
?>
Output:
30 is positive
-20 is negative
0 is zero
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-number-positive-negative-zero-using-bit-operators/
317
Chapter 53
Input : n = 64
Output : Yes
Input : 75
Output : No
First solution
We calculate log8(n) of the number if it is an integer, then n is in power of 8. We use
trunc(n) function that finds closest integer for a double value.
C++
318
Chapter 53. Check if a number is power of 8 or not
/* check if i is an integer or not */
return (i - trunc(i) < 0.000001)
}
/* driver function */
int main()
{
int n = 65;
checkPowerof8(n) ? cout << "Yes" : cout << "No";
return 0;
}
Java
Output :
No
319
Chapter 53. Check if a number is power of 8 or not
Second solution
A number is power of 8 if following conditions are satisfied.
1. The number is power of two. A number is power of two if it has only one set bit, i.e.,
bitwise and of n and n-1 is 0.
2. The number has its only set bit at position 0 or 3 or 6 or …. 30 [For a 32 bit num-
ber]. To check the position of its set bit we can use a mask (0xB6DB6DB6)16 =
(10110110110110110110110110110110)2 .
C++
Output :
No
Improved By : Sam007
Source
https://www.geeksforgeeks.org/check-number-power-8-not/
320
Chapter 54
Input : 9
Output : Yes
(9)10 = (1001)2
Input : 10
Output : No
(10)10 = (1010)2
1. Get the number obtained by reversing the bits in the binary representation of n. Refer
this post. Let it be rev.
2. If n == rev, then print “Yes” else “No”.
C++
321
Chapter 54. Check if actual binary representation of a number is palindrome
322
Chapter 54. Check if actual binary representation of a number is palindrome
Java
323
Chapter 54. Check if actual binary representation of a number is palindrome
{
long n = 9;
if (isPalindrome(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Sagar Shukla
Python3
324
Chapter 54. Check if actual binary representation of a number is palindrome
return (n == rev)
# Driver program to test above
n = 9
if (isPalindrome(n)) :
print("Yes")
else :
print("No")
# This code is contributed by Nikita Tiwari.
C#
325
Chapter 54. Check if actual binary representation of a number is palindrome
{
// get the number by reversing
// bits in the binary
// representation of 'n'
long rev = reverseBits(n);
return (n == rev);
}
// Driver function
public static void Main()
{
long n = 9;
if (isPalindrome(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP implementation to check
// whether binary representation
// of a number is palindrome or not
// function to reverse bits of a number
function reverseBits($n)
{
$rev = 0;
// traversing bits of 'n'
// from the right
while ($n > 0)
{
// bitwise left shift 'rev' by 1
$rev <<= 1;
// if current bit is '1'
if ($n & 1 == 1)
$rev ^= 1;
// bitwise right shift 'n' by 1
326
Chapter 54. Check if actual binary representation of a number is palindrome
$n >>= 1;
}
// required number
return $rev;
}
// function to check whether
// binary representation of a
// number is palindrome or not
function isPalindrome($n)
{
// get the number by reversing
// bits in the binary representation
// of 'n'
$rev = reverseBits($n);
return ($n == $rev);
}
// Driver code
$n = 9;
if (isPalindrome($n))
echo "Yes";
else
echo "No";
return 0;
// This code is contributed by mits
?>
Output :
Yes
Time Complexity: O(num), where num is the number of bits in the binary representation
of n.
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/check-actual-binary-representation-number-palindrome/
327
Chapter 55
Input : 7
Output : Yes
(7)10 = (111)2
Input : 14
Output : No
Method 1: If n = 0, then answer is ‘No’. Else perform the two operations until n becomes
0.
While (n > 0)
If n & 1 == 0,
return 'No'
n >> 1
If loop terminates without returning ‘No’, then all bits are set in the binary representation
of n.
C++
328
Chapter 55. Check if all bits of a number are set
Java
329
Chapter 55. Check if all bits of a number are set
Python3
# Python implementation
# to check whether every
# digit in the binary
# representation of the
# given number is set or not
# function to check if
# all the bits are set
# or not in the binary
# representation of 'n'
def areAllBitsSet(n):
330
Chapter 55. Check if all bits of a number are set
C#
// C# implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
using System;
class GFG
{
// function to check if
// all the bits are set
// or not in the binary
// representation of 'n'
static String areAllBitsSet(int n)
{
// all bits are not set
if (n == 0)
return "No";
331
Chapter 55. Check if all bits of a number are set
PHP
<?php
// PHP implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
// function to check if all the
// bits are set or not in the
// binary representation of 'n'
function areAllBitsSet($n)
{
// all bits are not set
if ($n == 0)
return "No";
// loop till n becomes '0'
while ($n > 0)
{
// if the last bit is not set
if (($n & 1) == 0)
332
Chapter 55. Check if all bits of a number are set
return "No";
// right shift 'n' by 1
$n = $n >> 1;
}
// all bits are set
return "Yes";
}
// Driver Code
$n = 7;
echo areAllBitsSet($n);
// This code is contributed by aj_36
?>
Output :
Yes
Time Complexity : O(d), where ‘d’ is the number of bits in the binary representation of
n.
C++
333
Chapter 55. Check if all bits of a number are set
// if true, then all bits are set
if (((n + 1) & n) == 0)
return "Yes";
// else all bits are not set
return "No";
}
// Driver program to test above
int main()
{
int n = 7;
cout << areAllBitsSet(n);
return 0;
}
Java
334
Chapter 55. Check if all bits of a number are set
}
// This code is contributed by vt_m
Python3
# Python implementation to
# check whether every
# digit in the binary
# representation of the
# given number is set or not
# function to check if
# all the bits are set
# or not in the binary
# representation of 'n'
def areAllBitsSet(n):
# all bits are not set
if (n == 0):
return "No"
# if true, then all bits are set
if (((n + 1) & n) == 0):
return "Yes"
# else all bits are not set
return "No"
# Driver program to test above
n = 7
print(areAllBitsSet(n))
# This code is contributed
# by Anant Agarwal.
C#
// C# implementation to check
// whether every digit in the
// binary representation of
// the given number is set or not
using System;
class GFG
335
Chapter 55. Check if all bits of a number are set
{
// function to check if all the
// bits are set or not in the
// binary representation of 'n'
static String areAllBitsSet(int n)
{
// all bits are not set
if (n == 0)
return "No";
// if true, then all
// bits are set
if (((n + 1) & n) == 0)
return "Yes";
// else all bits are not set
return "No";
}
// Driver Code
static public void Main ()
{
int n = 7;
Console.WriteLine(areAllBitsSet(n));
}
}
// This code is contributed by m_kit
PHP
<?php
// PHP implementation to check
// whether every digit in the
// binary representation of the
// given number is set or not
// function to check if all
// the bits are set or not in
// the binary representation of 'n'
function areAllBitsSet($n)
{
// all bits are not set
if ($n == 0)
return "No";
// if true, then all
336
Chapter 55. Check if all bits of a number are set
Output :
Yes
References:
https://www.careercup.com/question?id=9503107
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-bits-number-set/
337
Chapter 56
Check if binary representation of a given number and its complement are anagram - Geeks-
forGeeks
Given a positive number you need to check whether it’s complement and the number are
anagrams or not.
Examples:
Input : a = 4294967295
Output : Yes
Binary representation of 'a' and it's
complement are anagrams of each other
Input : a = 4
Output : No
338
Chapter 56. Check if binary representation of a given number and its complement are
anagram
Output:
339
Chapter 56. Check if binary representation of a given number and its complement are
anagram
Efficient Approach: Just count the number of 1’s present in the bit representation of the
given number. If number of 1’s present are 32 then it’s complement will also have 32 1’s in
it’s bit representation and they will be anagrams of each other.
Output:
Note:
1. The answer is only dependent on the number, in the above approach we don’t even find
the need to obtain the complement of the number.
2. The above code uses GCC specific functions. If we wish to write code for other compilers,
we may use Count set bits in an integer.
Source
https://www.geeksforgeeks.org/check-binary-representation-given-number-complement-anagram/
340
Chapter 57
#include<iostream>
using namespace std;
// This function returns true if k'th bit in x is set (or 1).
// For example if x (0010) is 2 and k is 2, then it returns true
bool isKthBitSet(unsigned int x, unsigned int k)
341
Chapter 57. Check if binary representation of a number is palindrome
{
return (x & (1 << (k-1)))? true: false;
}
// This function returns true if binary representation of x is
// palindrome. For example (1000...001) is paldindrome
bool isPalindrome(unsigned int x)
{
int l = 1; // Initialize left position
int r = sizeof(unsigned int)*8; // initialize right position
// One by one compare bits
while (l < r)
{
if (isKthBitSet(x, l) != isKthBitSet(x, r))
return false;
l++; r--;
}
return true;
}
// Driver program to test above function
int main()
{
unsigned int x = 1<<15 + 1<<16;
cout << isPalindrome(x) << endl;
x = 1<<31 + 1;
cout << isPalindrome(x) << endl;
return 0;
}
Output:
1
1
This article is contributed by Saurabh Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/check-binary-representation-number-palindrome/
342
Chapter 58
Input : a = 8, b = 4
Output : Yes
Binary representations of both
numbers have same 0s and 1s.
Input : a = 4, b = 5
Output : No
Simple Approach:
1. Find Binary Representation of ‘a’ and ‘b’ using simple decimal to binary representation
technique.
2. Check if two binary representations are anagram
C/C++
343
Chapter 58. Check if binary representations of two numbers are anagram
const int SIZE = 8 * sizeof(ull);
bool bit_anagram_check(ull a, ull b)
{
// Find reverse binary representation of a
// and store it in binary_a[]
int i = 0, binary_a[SIZE] = { 0 };
while (a > 0) {
binary_a[i] = a % 2;
a /= 2;
i++;
}
// Find reverse binary representation of b
// and store it in binary_a[]
int j = 0, binary_b[SIZE] = { 0 };
while (b > 0) {
binary_b[j] = b % 2;
b /= 2;
j++;
}
// Sort two binary representations
sort(binary_a, binary_a + SIZE);
sort(binary_b, binary_b + SIZE);
// Compare two sorted binary representations
for (int i = 0; i < SIZE; i++)
if (binary_a[i] != binary_b[i])
return false;
return true;
}
// Driver code
int main()
{
ull a = 8, b = 4;
cout << bit_anagram_check(a, b) << endl;
return 0;
}
Java
344
Chapter 58. Check if binary representations of two numbers are anagram
import java.util.*;
class GFG
{
public static int SIZE = 8;
// Function to check if binary representation
// of two numbers are anagram
static int bit_anagram_check(long a, long b)
{
// Find reverse binary representation of a
// and store it in binary_a[]
int i = 0;
long[] binary_a = new long[SIZE];
Arrays.fill(binary_a, 0);
while (a > 0)
{
binary_a[i] = a%2;
a /= 2;
i++;
}
// Find reverse binary representation of b
// and store it in binary_a[]
int j = 0;
long[] binary_b = new long[SIZE];
Arrays.fill(binary_b, 0);
while (b > 0)
{
binary_b[j] = b%2;
b /= 2;
j++;
}
// Sort two binary representations
Arrays.sort(binary_a);
Arrays.sort(binary_b);
// Compare two sorted binary representations
for (i = 0; i < SIZE; i++)
if (binary_a[i] != binary_b[i])
return 0;
return 1;
}
// driver program
public static void main (String[] args)
345
Chapter 58. Check if binary representations of two numbers are anagram
{
long a = 8, b = 4;
System.out.println(bit_anagram_check(a, b));
}
}
// Contributed by Pramod Kumar
Output:
Efficient Approach:
Just measure the number of 1’s present in the bit representation of both the numbers, if
number of 1’s present in their bit representation are same then they are anagrams in their
bit representation else they are not.
C/C++
346
Chapter 58. Check if binary representations of two numbers are anagram
Java
–
Output:
Note that the above code uses GCC specific functions. If we wish to write code for other
compilers, we may use Count set bits in an integer.
Time Complexity : O (1)
Auxiliary Space : O (1) No extra space is getting used.
Source
https://www.geeksforgeeks.org/check-binary-representations-two-numbers-anagram/
347
Chapter 59
Input : 1 0 1 0
Output : NO
Explanation : (1 0 1 0) is 10 and hence
not a multiple of 3
Input : 1 1 0 0
Output : YES
Explanation : (1 1 0 0) is 12 and hence
a multiple of 3
Approach : One simple method is to convert the binary number into its decimal rep-
resentation and then check if it is a multiple of 3 or not. Now, when it comes to DFA
(Deterministic Finite Automata), there is no concept of memory i.e. you cannot store
the string when it is provided, so the above method would not be applicable. In simple
terms, a DFA takes a string as input and process it. If it reaches final state, it is accepted,
else rejected. As you cannot store the string, so input is taken character by character.
The DFA for given problem is :
348
Chapter 59. Check if binary string multiple of 3 using DFA
As, when a number is divided by 3, there are only 3 possibilities. The remainder can be
either 0, 1 or 2. Here, state 0 represents that the remainder when the number is divided
by 3 is 0. State 1 represents that the remainder when the number is divided by 3 is 1 and
similarly state 2 represents that the remainder when the number is divided by 3 is 2. So if
a string reaches state 0 in the end, it is accepted otherwise rejected.
Below is the implementation of above approach :
C++
349
Chapter 59. Check if binary string multiple of 3 using DFA
case '1':
if (digit == '0')
state = '2';
else
state = '0';
break;
// when state is 2
case '2':
if (digit == '0')
state = '1';
break;
}
}
// if final state is 0th state
if (state == '0')
return true;
return false;
}
// Driver's Code
int main()
{
// size of binary array
int size = 5;
// array of binary numbers
// Here it is 21 in decimal
char c[] = { '1', '0', '1', '0', '1' };
// if binary numbers are a multiple of 3
if (isMultiple3(c, size))
cout << "YES\n";
else
cout << "NO\n";
return 0;
}
Java
350
Chapter 59. Check if binary string multiple of 3 using DFA
351
Chapter 59. Check if binary string multiple of 3 using DFA
C#
// C# Program to illustrate
// DFA for multiple of 3
using System;
class GFG {
// checks if binary characters
// are multiple of 3
static bool isMultiple3(char []c, int size)
{
// initial state is 0th
char state = '0';
for (int i = 0; i < size; i++)
{
// storing binary digit
char digit = c[i];
switch (state)
{
// when state is 0
case '0':
if (digit == '1')
state = '1';
break;
// when state is 1
352
Chapter 59. Check if binary string multiple of 3 using DFA
case '1':
if (digit == '0')
state = '2';
else
state = '0';
break;
// when state is 2
case '2':
if (digit == '0')
state = '1';
break;
}
}
// if final state is 0th state
if (state == '0')
return true;
return false;
}
// Driver Code
public static void Main ()
{
// size of binary array
int size = 5;
// array of binary numbers
// Here it is 21 in decimal
char []c = { '1', '0', '1', '0', '1' };
// if binary numbers are a multiple of 3
if (isMultiple3(c, size))
Console.WriteLine ("YES");
else
Console.WriteLine ("NO");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to illustrate
// DFA for multiple of 3
353
Chapter 59. Check if binary string multiple of 3 using DFA
// checks if binary characters
// are multiple of 3
function isMultiple3($c,$size)
{
// initial state is 0th
$state = '0';
for ($i = 0; $i < $size; $i++)
{
// storing binary digit
$digit = $c[$i];
switch ($state)
{
// when state is 0
case '0':
if ($digit == '1')
$state = '1';
break;
// when state is 1
case '1':
if ($digit == '0')
$state = '2';
else
$state = '0';
break;
// when state is 2
case '2':
if ($digit == '0')
$state = '1';
break;
}
}
// if final state is 0th state
if ($state == '0')
return true;
return false;
}
// Drive Code
354
Chapter 59. Check if binary string multiple of 3 using DFA
Output:
YES
Source
https://www.geeksforgeeks.org/check-binary-string-multiple-3-using-dfa/
355
Chapter 60
Check if bits in range L to R of two numbers are complement of each other or not - Geeks-
forGeeks
Given two non-negative numbers a and b and two values l and r. The problem is to check
whether all bits at corresponding positions in the range l to r in both the given numbers
are complement of each other or not.
The bits are numbered from right to left, i.e., the least significant bit is considered to be at
first position.
Examples:
Input: a = 10, b = 5
l = 1, r = 3
Output: Yes
(10)10 = (1010)2
(5)10 = (101)2 = (0101)2
All the bits in the range 1 to 3 are complement of each other.
Input: a = 21, b = 13
l = 2, r = 4
Output: No
(21)10 = (10101)2
(13)10 = (1101)2 = (1101)2
All the bits in the range 2 to 4 are not complement of each other.
356
Chapter 60. Check if bits in range L to R of two numbers are complement of each other or
not
• Calculate xor_value = a ^ b.
• Check whether all the bits are set or not in the range l to r in xor_value. Refer this
post.
Source
https://www.geeksforgeeks.org/check-if-all-the-bits-of-two-numbers-that-lies-within-range-l-to-r-are-complement-o
C++
357
Chapter 60. Check if bits in range L to R of two numbers are complement of each other or
not
{
unsigned int xor_value = a ^ b;
return allBitsSetInTheGivenRange(xor_value, l, r);
}
// Driver Code
int main()
{
unsigned int a = 10, b = 5;
unsigned int l = 1, r = 3;
if (bitsAreComplement(a, b, l, r))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation to check
// whether all the bits in the
// given range of two numbers
// are complement of each other
class GFG
{
// function to check whether
// all the bits are set in
// the given range or not
static boolean allBitsSetInTheGivenRange(int n,
int l, int r)
{
// calculating a number ‘num’
// having ‘r’ number of bits
// and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1); // new number which will only //
have one or more set bits // in the range l to r and // nowhere else int new_num = n
& num; // if both are equal, // then all bits are set // in the given range if (num ==
new_num) return true; // else all bits are not set return false; } // function to check
whether all // the bits in the given range // of two numbers are complement // of each
other static boolean bitsAreComplement(int a, int b, int l, int r) { int xor_value = a ^
b; return allBitsSetInTheGivenRange(xor_value, l, r); } // Driver Code public static void
main(String []args) { int a = 10, b = 5; int l = 1, r = 3; if (bitsAreComplement(a, b, l, r))
System.out.println(”Yes”); else System.out.println(”No”); } } // This code is contributed
by Smitha [tabbyending]
Output:
358
Chapter 60. Check if bits in range L to R of two numbers are complement of each other or
not
Yes
359
Chapter 61
Check if bits of a number has count of consecutive set bits in increasing order - GeeksforGeeks
Given a integer n > 0, the task is to find whether in the bit pattern of integer count of
continuous 1’s are in increasing from left to right.
Examples :
Input:19
Output:Yes
Explanation: Bit-pattern of 19 = 10011,
Counts of continuous 1's from left to right
are 1, 2 which are in increasing order.
Input : 183
Output : yes
Explanation: Bit-pattern of 183 = 10110111,
Counts of continuous 1's from left to right
are 1, 2, 3 which are in increasing order.
A simple solution is to store binary representation of given number into a string, then
traverse from left to right and count the number of continuous 1’s. For every encounter of
0 check the value of previous count of continuous 1’s to that of current value, if the value
of previous count is greater than the value of current count then return False, Else when
string ends return True.
C++
360
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
361
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
}
// check for last sequence of continuous-1
if (prev_count > curr_count && (curr_count != 0))
return 0;
return 1;
}
// Driver code
int main()
{
int n = 179;
if (findContinuous1(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Output :
Yes
An efficient solution is to use decimal to binary conversion loop that divides number by
2 and take remainder as bit. This loop finds bits from right to left. So we check if right to
left is in decreasing order or not.
Below is the implementation.
C++
362
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
Java
363
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
// order.
static boolean areSetBitsIncreasing(int n)
{
// Initialize previous count
int prev_count = Integer.MAX_VALUE;
// We traverse bits from right to
// left and check if counts are
// decreasing order.
while (n > 0)
{
// Ignore 0s until we reach
// a set bit.
while (n > 0 && n % 2 == 0)
n = n/2;
// Count current set bits
int curr_count = 1;
while (n > 0 && n % 2 == 1)
{
n = n/2;
curr_count++;
}
// Compare current with previous
// and update previous.
if (curr_count >= prev_count)
return false;
prev_count = curr_count;
}
return true;
}
// Driver code
static public void main (String[] args)
{
int n = 10;
if (areSetBitsIncreasing(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
364
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
Python 3
365
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
# This code is contributed by Smitha
C#
366
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
// Driver code
static public void Main ()
{
int n = 10;
if (areSetBitsIncreasing(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to check if
// counts of consecutive
// 1s are increasing order.
// Returns true if n has
// counts of consecutive
// 1's are increasing order.
function areSetBitsIncreasing( $n)
{
// Initialize previous count
$prev_count = PHP_INT_MAX;
// We traverse bits from right
// to left and check if counts
// are decreasing order.
while ($n > 0)
{
// Ignore 0s until we
// reach a set bit.
while ($n > 0 && $n % 2 == 0)
$n = $n / 2;
// Count current set bits
$curr_count = 1;
while ($n > 0 and $n % 2 == 1)
{
$n = $n / 2;
$curr_count++;
}
367
Chapter 61. Check if bits of a number has count of consecutive set bits in increasing order
Output :
No
Source
https://www.geeksforgeeks.org/check-bits-number-count-consecutive-set-bits-increasing-order/
368
Chapter 62
Observe, for a number to be the power of 2, it should have only 1 set bit.
If n is 1, then we simply check if the number has the only single set bit.
For n is greater than one, our task becomes to choose those numbers from the array whose
bitwise AND leads to an only single bit set number. To do so, we search a position, at which
all elements in the set has a bit set at that position. For example, for set { 4 (100), 6 (110),
7 (111) }, at position 2 (from right to left, 0-based indexing) bit is set for all element. So,
doing bitwise AND gives 4, which is a power of 2.
Below is the implementation of this approach:
C++
369
Chapter 62. Check if bitwise AND of any subset is power of two
#include <bits/stdc++.h>
using namespace std;
const int NUM_BITS = 32;
// Check for power of 2 or not
bool isPowerOf2(int num)
{
return (num && !(num & (num - 1)));
}
// Check if there exist a subset whose bitwise AND
// is power of 2.
bool checkSubsequence(int arr[], int n)
{
// if there is only one element in the set.
if (n == 1)
return isPowerOf2(arr[0]);
// Finding a number with all bit sets.
int total = 0;
for (int i = 0; i < NUM_BITS; i++)
total = total | (1 << i);
// check all the positions at which the bit is set.
for (int i = 0; i < NUM_BITS; i++) {
int ans = total;
for (int j = 0; j < n; j++) {
// include all those elements whose
// i-th bit is set
if (arr[j] & (1 << i))
ans = ans & arr[j];
}
// check for the set contains elements
// make a power of 2 or not
if (isPowerOf2(ans))
return true;
}
return false;
}
// Driver Program
int main()
{
int arr[] = { 12, 13, 7 };
370
Chapter 62. Check if bitwise AND of any subset is power of two
Java
371
Chapter 62. Check if bitwise AND of any subset is power of two
int ans = total;
for (int j = 0; j < n; j++)
{
// include all those
// elements whose
// i-th bit is set
int p = arr[j] & (1 << i);
if (p == 0)
ans = ans & arr[j];
}
// check for the set
// contains elements
// make a power of 2
// or not
if (isPowerOf2(ans))
return true;
}
return false;
}
// Driver Code
public static void main(String args[])
{
int []arr = {12, 13, 7};
int n = arr.length;
if (checkSubsequence(arr, n))
System.out.println("YES");
else
System.out.println("NO");
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
372
Chapter 62. Check if bitwise AND of any subset is power of two
# Check if there exist a subset whose bitwise AND
# is power of 2.
def checkSubsequence(arr, n):
# if there is only one element in the set.
if (n == 1):
return isPowerOf2(arr[0])
# Finding a number with all bit sets.
total = 0
for i in range(0, NUM_BITS):
total = total | (1 << i)
# check all the positions at which the bit is set.
for i in range(0, NUM_BITS):
ans = total
for j in range(0, n):
# include all those elements whose
# i-th bit is set
if (arr[j] & (1 << i)):
ans = ans & arr[j]
# check for the set contains elements
# make a power of 2 or not
if (isPowerOf2(ans)):
return True
return False
# Driver Program
arr = [ 12, 13, 7 ]
n = len(arr)
if (checkSubsequence(arr, n)):
print ("YES\n")
else:
print ("NO\n")
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
373
Chapter 62. Check if bitwise AND of any subset is power of two
class GFG {
static int NUM_BITS = 32;
// Check for power of 2 or not
static bool isPowerOf2(int num)
{
if(num != 0 && (num & (num - 1)) == 0)
return true;
return false;
}
// Check if there exist a
// subset whose bitwise AND
// is power of 2.
static bool checkSubsequence(int []arr, int n)
{
// if there is only one
// element in the set.
if (n == 1)
return isPowerOf2(arr[0]);
// Finding a number with
// all bit sets.
int total = 0;
for (int i = 0; i < NUM_BITS; i++)
total = total | (1 << i);
// check all the positions
// at which the bit is set.
for (int i = 0; i < NUM_BITS; i++)
{
int ans = total;
for (int j = 0; j < n; j++)
{
// include all those
// elements whose
// i-th bit is set
int p = arr[j] & (1 << i);
if (p == 0)
ans = ans & arr[j];
}
// check for the set
374
Chapter 62. Check if bitwise AND of any subset is power of two
PHP
<?php
// PHP Program to check if
// Bitwise AND of any subset
// is power of two
// Check for power of 2 or not
function isPowerOf2($num)
{
return ($num && !($num & ($num - 1)));
}
// Check if there exist a
// subset whose bitwise AND
// is power of 2.
function checkSubsequence($arr, $n)
{
$NUM_BITS = 32;
// if there is only one
// element in the set.
if ($n == 1)
return isPowerOf2($arr[0]);
375
Chapter 62. Check if bitwise AND of any subset is power of two
// Finding a number with
// all bit sets.
$total = 0;
for($i = 0; $i < $NUM_BITS; $i++)
$total = $total | (1 << $i);
// check all the positions at
// which the bit is set.
for($i = 0; $i < $NUM_BITS; $i++)
{
$ans = $total;
for ($j = 0; $j < $n; $j++)
{
// include all those
// elements whose
// i-th bit is set
if ($arr[$j] & (1 << $i))
$ans = $ans & $arr[$j];
}
// check for the set
// contains elements
// make a power of 2 or not
if (isPowerOf2($ans))
return true;
}
return false;
}
// Driver Code
$arr= array(12, 13, 7);
$n = sizeof($arr) / sizeof($arr[0]);
if (checkSubsequence($arr, $n))
echo "YES";
else
echo "NO";
// This code is contributed by mits
?>
Output:
YES
376
Chapter 62. Check if bitwise AND of any subset is power of two
Reference:
https://stackoverflow.com/questions/35990794/subset-of-array-a-in-which-if-we-do-and-of-all-elements-of-that-sub
Improved By : Mithun Kumar, manishshaw1
Source
https://www.geeksforgeeks.org/check-bitwise-subset-power-two/
377
Chapter 63
A naive solution is to first concatenate both sequences and then check if the resultant
sequence is balanced or not using a stack. First, check if s1 + s2 is balanced or not. If not,
then check if s2 + s1 is balanced or not. To check if a given sequence of brackets is balanced
or not using a stack, the following algorithm can be used.
378
Chapter 63. Check if concatenation of two strings is balanced or not
3. After complete traversal, if there is some starting bracket left in stack then “not
balanced”.
C++
379
Chapter 63. Check if concatenation of two strings is balanced or not
return true;
}
// Function to check if string obtained by
// concatenating two bracket sequences is
// balanced or not.
bool isBalancedSeq(string s1, string s2)
{
// Check if s1 + s2 is balanced or not.
if (isBalanced(s1 + s2))
return true;
// Check if s2 + s1 is balanced or not.
return isBalanced(s2 + s1);
}
// Driver code.
int main()
{
string s1 = ")()(())))";
string s2 = "(()(()(";
if (isBalancedSeq(s1, s2))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}
Output:
Balanced
380
Chapter 63. Check if concatenation of two strings is balanced or not
number of opening brackets, then the last closing bracket will not have a matching
opening bracket (that is why the count is more) in s.
• If the sequence is balanced then at the end of traversal, the number of opening brackets
in s is equal to the number of closing brackets in s.
C++
381
Chapter 63. Check if concatenation of two strings is balanced or not
Java
382
Chapter 63. Check if concatenation of two strings is balanced or not
// is balanced bracket
// sequence or not.
static boolean isBalanced(String s)
{
// To store result of comparison
// of count of opening brackets
// and closing brackets.
int cnt = 0;
int n = s.length();
for (int i = 0; i < n; i++)
{
// If current bracket is
// an opening bracket,
// then increment count.
if (s.charAt(i) =='(')
{
cnt = cnt + 1;
}
// If current bracket is a
// closing bracket, then
// decrement count and check
// if count is negative.
else
{
cnt = cnt - 1;
if (cnt < 0)
return false;
}
}
// If count is positive then
// some opening brackets are
// not balanced.
if (cnt > 0)
return false;
return true;
}
// Function to check if string
// obtained by concatenating
// two bracket sequences is
// balanced or not.
static boolean isBalancedSeq(String s1,
String s2)
383
Chapter 63. Check if concatenation of two strings is balanced or not
{
// Check if s1 + s2 is
// balanced or not.
if (isBalanced(s1 + s2))
return true;
// Check if s2 + s1 is
// balanced or not.
return isBalanced(s2 + s1);
}
// Driver code
public static void main(String [] args)
{
String s1 = ")()(())))";
String s2 = "(()(()(";
if (isBalancedSeq(s1, s2))
{
System.out.println("Balanced");
}
else
{
System.out.println("Not Balanced");
}
}
}
// This code is contributed
// by Shivi_Aggarwal
Python3
384
Chapter 63. Check if concatenation of two strings is balanced or not
cnt = 0
n = len(s)
for i in range(0, n):
if (s[i] == '('):
cnt = cnt + 1
else :
cnt = cnt - 1
if (cnt < 0):
return False
if (cnt > 0):
return False
return True
def isBalancedSeq(s1, s2):
if (isBalanced(s1 + s2)):
return True
return isBalanced(s2 + s1)
# Driver code
a = ")()(())))";
b = "(()(()(";
if (isBalancedSeq(a, b)):
print("Balanced")
else:
print("Not Balanced")
# This code is contributed
# by Shivi_Aggarwal
Output:
Balanced
Source
https://www.geeksforgeeks.org/check-if-concatenation-of-two-strings-is-balanced-or-not/
385
Chapter 64
Input : 1 1 2 2
Output : Yes
Input : 1 2 3 4
Output : No
Approach 1 :- We will check, if any of the two integers are equal and make sure rest of
two are also equal using few if else conditions.
C++
386
Chapter 64. Check if given four integers (or sides) make rectangle
if (a == b == c == d)
return true;
else if (a == b && c == d)
return true;
else if (a == d && c == b)
return true;
else if (a == c && d == b)
return true;
else
return false;
}
// Driver code
int main()
{
int a, b, c, d;
a = 1, b = 2, c = 3, d = 4;
if (isRectangle(a, b, c, d))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
387
Chapter 64. Check if given four integers (or sides) make rectangle
return true;
else
return false;
}
// Driver code
public static void main(String[] args)
{
int a = 1, b = 2, c = 3, d = 4;
if (isRectangle(a, b, c, d))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by prerna saini.
Python3
388
Chapter 64. Check if given four integers (or sides) make rectangle
# This code is contributed by Ansu Kumari.
C#
389
Chapter 64. Check if given four integers (or sides) make rectangle
Output :
No
C++
Java
390
Chapter 64. Check if given four integers (or sides) make rectangle
int c, int d)
{
if ((a ^ b ^ c ^ d) != 0)
return false;
else
return true;
}
// Driver code
public static void main(String[] args)
{
int a, b, c, d;
a = 3; b = 2; c = 3; d = 2;
if (isRectangle(a, b, c, d))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
C#
391
Chapter 64. Check if given four integers (or sides) make rectangle
Output :
Yes
Source
https://www.geeksforgeeks.org/check-given-four-integers-sides-make-rectangle/
392
Chapter 65
Input : n = 256, d = 16
Output : Yes
Input : n = 32, d = 16
Output : No
Method 1 Take log of the given number on base d, and if we get an integer then number
is power of d.
Method 2 Keep dividing the number by d, i.e, do n = n/d iteratively. In any iteration, if
n%d becomes non-zero and n is not 1 then n is not a power of d, otherwise n is a power of
d.
Method 3(Bitwise)
A number n is a power of d if following conditions are met.
a) There is only one bit set in the binary representation of n (Note : d is a power of 2)
b) The count of zero bits before the (only) set bit is a multiple of log2 (d).
For example: For n = 16 (10000) and d = 4, 16 is a power of 4 because there is only one
bit set and count of 0s before the set bit is 4 which is a multiple of log2 (4).
C++
393
Chapter 65. Check if given number is a power of d where d is a power of 2
Java
394
Chapter 65. Check if given number is a power of d where d is a power of 2
// where d is power of 2.
class GFG
{
static int Log2n(int n)
{
return (n > 1)? 1 +
Log2n(n / 2): 0;
}
static boolean isPowerOfd(int n,
int d)
{
int count = 0;
/* Check if there is
only one bit set in n*/
if (n > 0 && (n &
(n - 1)) == 0)
{
/* count 0 bits
before set bit */
while (n > 1)
{
n >>= 1;
count += 1;
}
/* If count is a multiple
of log2(d) then return
true else false*/
return (count %
(Log2n(d)) == 0);
}
/* If there are more
than 1 bit set then
n is not a power of 4*/
return false;
}
// Driver Code
public static void main(String[] args)
{
int n = 64, d = 8;
if (isPowerOfd(n, d))
System.out.println(n +
" is a power of " + d);
395
Chapter 65. Check if given number is a power of d where d is a power of 2
else
System.out.println(n +
" is not a power of " + d);
}
}
// This code is contributed by mits
Python3
C#
396
Chapter 65. Check if given number is a power of d where d is a power of 2
// C# program to find if
// a number is power of d
// where d is power of 2.
using System;
class GFG
{
static int Log2n(int n)
{
return (n > 1)? 1 +
Log2n(n / 2): 0;
}
static bool isPowerOfd(int n,
int d)
{
int count = 0;
/* Check if there is
only one bit set in n*/
if (n > 0 && (n & (n - 1)) == 0)
{
/* count 0 bits
before set bit */
while (n > 1)
{
n >>= 1;
count += 1;
}
/* If count is a multiple
of log2(d) then return
true else false*/
return (count % (Log2n(d)) == 0);
}
/* If there are more than
1 bit set then n is not
a power of 4*/
return false;
}
// Driver Code
static void Main()
{
int n = 64, d = 8;
if (isPowerOfd(n, d))
Console.WriteLine("{0} is a " +
397
Chapter 65. Check if given number is a power of d where d is a power of 2
"power of {1}",
n, d);
else
Console.WriteLine("{0} is not a"+
" power of {1}",
n, d);
}
// This code is contributed by mits
}
PHP
<?php
// PHP program to find if a number
// is power of d where d is power of 2.
function Log2n($n)
{
return ($n > 1)? 1 +
Log2n($n / 2): 0;
}
function isPowerOfd($n, $d)
{
$count = 0;
// Check if there is only
// one bit set in n
if ($n && !($n & ($n - 1)))
{
// count 0 bits
// before set bit
while ($n > 1)
{
$n >>= 1;
$count += 1;
}
/* If count is a multiple of log2(d)
then return true else false*/
return ($count%(Log2n($d)) == 0);
}
/* If there are more than 1 bit set
then n is not a power of 4*/
return false;
398
Chapter 65. Check if given number is a power of d where d is a power of 2
}
// Driver Code
$n = 64;
$d = 8;
if (isPowerOfd($n, $d))
echo $n," ","is a power of ", $d;
else
echo $n," ","is not a power of ", $d;
// This code is contributed by m_kit
?>
Output:
64 is a power of 8
Source
https://www.geeksforgeeks.org/check-given-number-power-d-d-power-2/
399
Chapter 66
Input : n = 8, m = 2
Output : Yes
Input : n = 14, m = 3
Output : No
Approach: If a number is divisible by 2 then it has its least significant bit (LSB) set to
0, if divisible by 4 then two LSB’s set to 0, if by 8 then three LSB’s set to 0 and so on.
Keeping this in mind, a number n is divisible by 2m if (n & ((1 << m) – 1)) is equal to
0 else not.
C++
400
Chapter 66. Check if n is divisible by power of 2 without using arithmetic operators
// is divisible by pow(2, m)
bool isDivBy2PowerM(unsigned int n,
unsigned int m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if ((n & ((1 << m) - 1)) == 0)
return true;
// n is not divisible
return false;
}
// Driver program to test above
int main()
{
unsigned int n = 8, m = 2;
if (isDivBy2PowerM(n, m))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
401
Chapter 66. Check if n is divisible by power of 2 without using arithmetic operators
Python3
C#
402
Chapter 66. Check if n is divisible by power of 2 without using arithmetic operators
class GFG {
// function to chech whether n
// is divisible by pow(2, m)
static bool isDivBy2PowerM(int n, int m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if ((n & ((1 << m) - 1)) == 0)
return true;
// n is not divisible
return false;
}
/* Driver program to test above function */
public static void Main()
{
int n = 8, m = 2;
if (isDivBy2PowerM(n, m))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP implementation to chech whether
// n is divisible by pow(2, m)
// function to chech whether n
// is divisible by pow(2, m)
function isDivBy2PowerM($n, $m)
{
// if expression results to 0, then
// n is divisible by pow(2, m)
if (($n & ((1 << $m) - 1)) == 0)
return true;
// n is not divisible
return false;
}
403
Chapter 66. Check if n is divisible by power of 2 without using arithmetic operators
// Driver Code
$n = 8;
$m = 2;
if (isDivBy2PowerM($n, $m))
echo "Yes";
else
echo "No";
// This code is contributed by ajit
?>
Output:
Yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-n-divisible-power-2-without-using-arithmetic-operators/
404
Chapter 67
Input : a = 10, b = 5
Output : Yes
(10)10 = (1010)2
1's complement of 10 is
= (0101)2 = (101)2 = (5)10
Input : a = 1, b = 14
Output : Yes
(14)10 = (1110)2
1's complement of 14 is
= (0001)2 = (1)2 = (1)10
1. Calculate n = a ^ b.
2. Check whether all bits are set in the binary representation of n. Refer this post.
CPP
405
Chapter 67. Check if one of the numbers is one’s complement of the other
Java
// Java implementation to
// check if one of the two
// numbers is one's complement
// of the other
406
Chapter 67. Check if one of the numbers is one’s complement of the other
import java.util.*;
import java.lang.*;
public class GfG{
// function to check
// if all the bits are set
// or not in the binary
// representation of 'n'
public static boolean areAllBitsSet(long n)
{
// all bits are not set
if (n == 0)
return false;
// if true, then all bits are set
if (((n + 1) & n) == 0)
return true;
// else all bits are not set
return false;
}
// function to check if
// one of the two numbers
// is one's complement
// of the other
public static boolean isOnesComplementOfOther(long a,
long b)
{
return areAllBitsSet(a ^ b);
}
// Driver function
public static void main(String argc[]){
long a = 10, b = 5;
if (isOnesComplementOfOther(a,b))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Sagar Shukla
407
Chapter 67. Check if one of the numbers is one’s complement of the other
Python3
C#
// C# implementation to check
408
Chapter 67. Check if one of the numbers is one’s complement of the other
409
Chapter 67. Check if one of the numbers is one’s complement of the other
PHP
<?php
// PHP implementation to
// check if one of the two
// numbers is one's complement
// of the other
// function to check if
// all the bits are set
// or not in the binary
// representation of 'n'
function areAllBitsSet($n)
{
// all bits are not set
if ($n == 0)
return false;
// if true, then all
// bits are set
if ((($n + 1) & $n) == 0)
return true;
// else all bits
// are not set
return false;
}
// function to check if
// one of the two numbers
// is one's complement of
// the other
function isOnesComplementOfOther($a,
$b)
{
return areAllBitsSet($a ^ $b);
}
// Driver Code
$a = 10; $b = 5;
if (isOnesComplementOfOther($a, $b))
echo "Yes";
else
echo "No";
// This code is contributed by anuj_67.
410
Chapter 67. Check if one of the numbers is one’s complement of the other
?>
Output:
Yes
Improved By : vt_m
Source
https://www.geeksforgeeks.org/check-one-numbers-ones-complement/
411
Chapter 68
Check if two numbers are bit rotations of each other or not - GeeksforGeeks
Given two positive integers x and y, check if one integer is obtained by rotating bits of other.
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the
bits that fall off at one end are put back to the other end.
More information on bit rotation can be found here
Example 1 :
Input : a = 8, b = 1
Output : yes
Explanation :
Represntation of a = 8 : 0000 0000 0000 0000 0000 0000 0000 1000
Represntation of b = 1 : 0000 0000 0000 0000 0000 0000 0000 0001
If we rotate a by 3 units right we get b, hence answer is yes
Example 2 :
Explanation :
412
Chapter 68. Check if two numbers are bit rotations of each other or not
Represntation of a = 122 : 0000 0000 0000 0000 0000 0000 0111 1010
Represntation of b = 2147483678 : 1000 0000 0000 0000 0000 0000 0001 1110
If we rotate a by 2 units right we get b, hence answer is yes
Since total bits in which x or y can be represented is 32 since x, y > 0 and x, y < 2^32.
So we need to find all 32 possible rotations of x and compare it with y till x and y are not
equal.
To do this we use a temporary variable x64 with 64 bits which is result of concatenation of
x to x ie..
x64 has first 32 bits same as bits of x and last 32 bits are also same as bits of x64.
Then we keep on shifting x64 by 1 on right side and compare the rightmost 32 bits of x64
with y.
In this way we’ll be able to get all the possible bits combination due to rotation.
Here is implementation of above algorithm.
C++
413
Chapter 68. Check if two numbers are bit rotations of each other or not
PHP
<?php
// PHP program to check if two
// numbers are bit rotations of
// each other.
// function to check if two
// numbers are equal after
// bit rotation
function isRotation($x, $y)
{
// x64 has concatenation
// of x with itself.
$x64 = $x | ($x << 32);
while ($x64 >= $y)
{
// comapring only last 32 bits
if (($x64) == $y)
return 1;
// right shift by 1 unit
$x64 >>= 1;
}
return -1;
}
// Driver Code
$x = 122;
$y = 2147483678;
if (isRotation($x, $y))
echo "yes" ,"\n";
else
echo "no" ,"\n";
// This code is contributed by aj_36
?>
414
Chapter 68. Check if two numbers are bit rotations of each other or not
Output :
yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-two-numbers-bit-rotations-not/
415
Chapter 69
Check if two numbers are equal without using arithmetic and comparison operators - Geeks-
forGeeks
Following are not allowed to use
1) Arithmetic and Comparison Operators
2) String functions
The idea is to use XOR operator. XOR of two numbers is 0 if the numbers are same,
otherwise non-zero.
C++
416
Chapter 69. Check if two numbers are equal without using arithmetic and comparison
operators
}
// Driver Code
int main()
{
// Calling function
areSame(10, 20);
}
Java
Python 3
417
Chapter 69. Check if two numbers are equal without using arithmetic and comparison
operators
C#
PHP
<?php
418
Chapter 69. Check if two numbers are equal without using arithmetic and comparison
operators
Output :
Not Same
Source: https://www.geeksforgeeks.org/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum/
Improved By : Smitha Dinesh Semwal, nitin mittal
Source
https://www.geeksforgeeks.org/check-if-two-numbers-are-equal-without-using-arithmetic-and-comparison-operator
419
Chapter 70
Check if two numbers are equal without using comparison operators - GeeksforGeeks
Following are not allowed to use
1) Comparison Operators
2) String functions
Examples:
Method 1: The idea is to use XOR operator. XOR of two numbers is 0 if the numbers
are same, otherwise non-zero.
C++
#include <iostream>
using namespace std;
// Finds if a and b are same.
void areSame(int a, int b)
{
if (a^b)
420
Chapter 70. Check if two numbers are equal without using comparison operators
Java
class GFG
{
// Finds if a and b are same
static void areSame(int a,int b)
{
if( (a ^ b) != 0 )
System.out.println("Not Same");
else
System.out.println("Same");
}
public static void main(String args[])
{
areSame(10,20);
}
}
// This code is contributed by Sumit Ghosh
Python
C#
421
Chapter 70. Check if two numbers are equal without using comparison operators
// C# program to check if 2
// numbers are same
using System;
class GFG
{
// Finds if a and b are same
static void areSame(int a, int b)
{
if( (a ^ b) != 0 )
Console.Write("Not Same");
else
Console.Write("Same");
}
// Driver code
public static void Main()
{
// Calling Function
areSame(10, 20);
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// Finds if a and b are same.
function areSame($a, $b)
{
if ($a ^ $b)
echo "Not Same";
else
echo "Same";
}
// Driver Code
areSame(10, 20);
// This code is contributed by nitin mittal
?>
Output:
422
Chapter 70. Check if two numbers are equal without using comparison operators
Not Same
Method 2: We can subtract the numbers. Same numbers yield 0. If answer is not 0,
numbers are not same.
C++
Java
423
Chapter 70. Check if two numbers are equal without using comparison operators
}
}
//This code is contributed by Sumit Ghosh
Python
C#
// C# code to check if 2
// numbers are same
using System;
class GFG
{
// Finds if a and b are same
static void areSame(int a, int b)
{
if ((a - b) == 0)
Console.Write("Same");
else
Console.Write("Not Same");
}
// Driver code
public static void Main()
{
// Calling Function
areSame(10, 20);
}
}
// This code is contributed by Nitin Mittal.
424
Chapter 70. Check if two numbers are equal without using comparison operators
PHP
<?php
// PHP code to check if 2
// numbers are same
// Finds if a and b are same
function areSame($a, $b)
{
if (!($a - $b))
echo "Same";
else
echo "Not Same";
}
// Driver code
areSame(10, 20);
// This code is contributed by nitin mittal
?>
Output:
Not Same
Source
https://www.geeksforgeeks.org/check-two-numbers-equal-without-using-comparison-operators/
425
Chapter 71
Check in binary array the number represented by a subarray is odd or even - GeeksforGeeks
Given a array such that all its terms is either 0 or 1.You need to tell the number represented
by a subarray a[l..r] is odd or even
Examples :
The important point to note here is all the odd numbers in binary form have 1 as their
rightmost bit and all even numbers have 0 as their rightmost bit.
The reason is simple all other bits other than rightmost bit have even values and sum of
even numbers is always even .Now the rightmost bit can have value either 1 or 0 as we
know even + odd = odd so when right most bit is 1 the number is odd and when it is 0 the
number is even.
So to solve this problem we have to just check if a[r] is 0 or 1 and accordingly print odd or
even
426
Chapter 71. Check in binary array the number represented by a subarray is odd or even
C++
Java
427
Chapter 71. Check in binary array the number represented by a subarray is odd or even
// driver code
public static void main (String[] args)
{
int arr[] = {1, 1, 0, 1};
int n = arr.length;
checkEVENodd (arr, n, 1, 3);
}
}
// This article is contributed by vt_m.
Python3
C#
428
Chapter 71. Check in binary array the number represented by a subarray is odd or even
PHP
<?php
// PHP program to find if a subarray
// is even or odd.
// prints if subarray is even or odd
function checkEVENodd ($arr, $n, $l, $r)
{
// if arr[r] = 1 print odd
if ($arr[$r] == 1)
echo "odd", "\n";
// if arr[r] = 0 print even
else
echo "even", "\n";
}
// Driver code
$arr = array(1, 1, 0, 1);
$n = sizeof($arr);
checkEVENodd ($arr, $n, 1, 3);
429
Chapter 71. Check in binary array the number represented by a subarray is odd or even
Output :
odd
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-binary-array-number-represented-subarray-odd-even/
430
Chapter 72
Input : n = 5, k = 1
Output : SET
5 is represented as 101 in binary
and has its first bit set.
Input : n = 2, k = 3
Output : NOT SET
2 is represented as 10 in binary,
all higher i.e. beyond MSB,
bits are NOT SET.
Example:
431
Chapter 72. Check whether K-th bit is set or not
n = 75 and k = 4
temp = 1 << (k-1) = 1 << 3 = 8
Binary Representation of temp = 0..00001000
Binary Representation of n = 0..01001011
Since bitwise AND of n and temp is non-zero,
result is SET.
C++
Java
432
Chapter 72. Check whether K-th bit is set or not
Python3
C#
433
Chapter 72. Check whether K-th bit is set or not
int n = 5, k = 1;
isKthBitSet(n, k);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to check if
// k-th bit of a given
// number is set or not
function isKthBitSet($n, $k)
{
if ($n & (1 << ($k - 1)))
echo "SET";
else
echo "NOT SET";
}
// Driver code
$n = 5; $k = 1;
isKthBitSet($n, $k);
// This code is contributed
// by akt_mit
?>
Output:
SET
434
Chapter 72. Check whether K-th bit is set or not
void isKthBitSet(int n, int k)
{
if ((n >> (k - 1)) & 1)
cout << "SET";
else
cout << "NOT SET";
}
// Driver code
int main()
{
int n = 5, k = 1;
isKthBitSet(n, k);
return 0;
}
Java
435
Chapter 72. Check whether K-th bit is set or not
C#
PHP
<?php
// PHP program to check
// if k-th bit of a given
// number is set or not
// using right shift operator.
function isKthBitSet($n, $k)
{
if (($n >> ($k - 1)) & 1)
echo "SET";
else
echo "NOT SET";
}
436
Chapter 72. Check whether K-th bit is set or not
// Driver code
$n = 5; $k = 1;
isKthBitSet($n, $k);
// This code is contributed
// by akt_mit
?>
Output:
SET
Source
https://www.geeksforgeeks.org/check-whether-k-th-bit-set-not/
437
Chapter 73
Examples :
438
Chapter 73. Check whether a given number is even or odd
input: 2
output: even
input: 5
output: odd
C++
Java
439
Chapter 73. Check whether a given number is even or odd
{
int n = 101;
if(isEven(n) == true)
System.out.print("Even");
else
System.out.print("Odd");
}
}
// This code is contributed by rishabh_jain
Python3
C#
440
Chapter 73. Check whether a given number is even or odd
Console.WriteLine("Odd");
}
}
// This code is contributed by vt_m
PHP
<?php
// A simple PHP program to
// check for even or odd
// Returns true if n is
// even, else odd
function isEven($n)
{
return ($n % 2 == 0);
}
// Driver code
$n = 101;
if(isEven != true)
echo "Even";
else
echo "Odd";
// This code is contributed by Ajit
?>
Output :
Odd
A better solution is to use bitwise operators. We need to check whether last bit is 1 or
not. If last bit is 1 then number is odd, otherwise always even.
Explanation:
input : 5 // odd
00000101
& 00000001
--------------
00000001
--------------
441
Chapter 73. Check whether a given number is even or odd
input : 8 //even
00001000
& 00000001
--------------
00000000
--------------
C++
Java
442
Chapter 73. Check whether a given number is even or odd
if((n & 1) == 0)
return true;
else
return false;
}
// Driver code
public static void main(String[] args)
{
int n = 101;
if(isEven(n) == true)
System.out.print("Even");
else
System.out.print("Odd");
}
}
// This code is contributed by rishabh_jain
Python3
C#
443
Chapter 73. Check whether a given number is even or odd
{
if((n & 1) == 0)
return true;
else
return false;
}
// Driver code
public static void Main()
{
int n = 101;
if(isEven(n) == true)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");
}
}
// This code is contributed by vt_m.
PHP
<?php
// A simple PHP program to
// check for even or odd
// Returns true if n is
// even, else odd
function isEven($n)
{
return (!($n & 1));
}
// Driver code
$n = 101;
if(isEven($n) == true)
echo "Even";
else
echo "Odd";
// This code is contributed by Smitha
?>
Output :
Odd
444
Chapter 73. Check whether a given number is even or odd
Source
https://www.geeksforgeeks.org/check-whether-given-number-even-odd/
445
Chapter 74
Check whether all the bits are set in the given range - GeeksforGeeks
Given a non-negative number n and two values l and r. The problem is to check whether
all the bits are set or not in the range l to r in the binary representation of n.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Examples:
Input : n = 22, l = 2, r = 3
Output : Yes
(22)10 = (10110)2
The bits in the range 2 to 3 are all set.
Input : n = 47, l = 2, r = 5
Output : No
(47)10 = (101111)2
The bits in the range 2 to 5 are all not set.
1. Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number
num having r number of bits and bits in the range l to r are the only set bits.
2. Calculate new_num = n & num.
3. If num == new_num, return “Yes” (all bits are set in the given range).
4. Else return “No” (all bits are not set in the given range).
C++
446
Chapter 74. Check whether all the bits are set in the given range
Java
447
Chapter 74. Check whether all the bits are set in the given range
{
// calculating a number 'num' having 'r'
// number of bits and bits in the range
// l to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 <<
(l - 1)) - 1);
// new number which will only have one
// or more set bits in the range l to r
// and nowhere else
int new_num = n & num;
// if both are equal, then all bits are
// set in the given range
if (num == new_num)
return "Yes";
// else all bits are not set
return "No";
}
//Driver code
public static void main (String[] args)
{
int n = 22;
int l = 2, r = 3;
System.out.print(allBitsSetInTheGivenRange(
n, l, r));
}
}
// This code is contributed by Anant Agarwal.
Python3
448
Chapter 74. Check whether all the bits are set in the given range
C#
449
Chapter 74. Check whether all the bits are set in the given range
PHP
<?php
// PHP implementation to check
// whether all the bits are set
// in the given range or not
// function to check whether
// all the bits are set in
// the given range or not
function allBitsSetInTheGivenRange($n, $l, $r)
{
// Calculating a number
// 'num' having 'r'
// number of bits and
// bits in the range l
// to r are the only
// set bits
$num = ((1 << $r) - 1) ^
((1 << ($l - 1)) - 1);
// new number which will
// only have one or more
// set bits in the range
// l to r and nowhere else
$new_num = $n & $num;
// if both are equal,
// then all bits are set
// in the given range
if ($num == $new_num)
return "Yes";
450
Chapter 74. Check whether all the bits are set in the given range
// else all bits
// are not set
return "No";
}
// Driver Code
$n = 22;
$l = 2;
$r = 3;
echo allBitsSetInTheGivenRange($n, $l, $r);
// This code is contributed by Ajit
?>
Output:
Yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-whether-bits-set-given-range/
451
Chapter 75
Check whether all the bits are unset in the given range - GeeksforGeeks
Given a non-negative number n and two values l and r. The problem is to check whether all
the bits are unset or not in the range l to r in the binary representation of n. The bits are
numbered from right to left, i.e., the least significant bit is considered to be at first position.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Examples:
Input : n = 17, l = 2, r = 4
Output : Yes
(17)10 = (10001)2
The bits in the range 2 to 4 are all unset.
Input : n = 39, l = 4, r = 6
Output : No
(39)10 = (100111)2
The bits in the range 4 to 6 are all not unset.
1. Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number
num having r number of bits and bits in the range l to r are the only set bits.
2. Calculate new_num = n & num.
3. If new_num == 0, return “Yes” (all bits are unset in the given range).
4. Else return “No” (all bits are not unset in the given range).
C++
452
Chapter 75. Check whether all the bits are unset in the given range
Java
453
Chapter 75. Check whether all the bits are unset in the given range
{
// function to check whether
// all the bits are unset in
// the given range or not
static boolean allBitsSetInTheGivenRange(int n,
int l,
int r)
{
// calculating a number 'num'
// having 'r' number of bits
// and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^
((1 << (l - 1)) - 1);
// new number which could only
// have one or more set bits in
// the range l to r and nowhere else
int new_num = n & num;
// if true, then all bits are
// unset in the given range
if (new_num == 0)
return true;
// else all bits are not
// unset in the given range
return false;
}
// Driver Code
public static void main(String[] args)
{
int n = 17;
int l = 2, r = 4;
if (allBitsSetInTheGivenRange(n, l, r))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed
// by Smitha
Python3
454
Chapter 75. Check whether all the bits are unset in the given range
C#
// C# implementation to check
// whether all the bits are
// unset in the given range or not
455
Chapter 75. Check whether all the bits are unset in the given range
using System;
class GFG
{
// function to check whether
// all the bits are unset in
// the given range or not
static bool allBitsSetInTheGivenRange(int n,
int l,
int r)
{
// calculating a number 'num'
// having 'r' number of bits
// and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^
((1 << (l - 1)) - 1);
// new number which could
// only have one or more
// set bits in the range
// l to r and nowhere else
int new_num = n & num;
// if true, then all
// bits are unset
// in the given range
if (new_num == 0)
return true;
// else all bits are not
// unset in the given range
return false;
}
// Driver Code
public static void Main()
{
int n = 17;
int l = 2, r = 4;
if (allBitsSetInTheGivenRange(n, l, r))
Console.Write("Yes");
else
Console.Write("No");
}
}
456
Chapter 75. Check whether all the bits are unset in the given range
PHP
Output:
Yes
Source
https://www.geeksforgeeks.org/check-whether-all-the-bits-are-unset-in-the-given-range/
457
Chapter 76
Check whether all the bits are unset in the given range or not - GeeksforGeeks
Given a non-negative number n and two values l and r. The problem is to check whether
all the bits are unset or not in the range l to r in the binary representation of n.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Examples:
Input : n = 17, l = 2, r = 4
Output : Yes
(17)10 = (10001)2
The bits in the range 2 to 4 are all unset.
Input : n = 36, l = 3, r = 5
Output : No
(36)10 = (100100)2
The bits in the range 3 to 5 are all not unset.
1. Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number
num having r number of bits and bits in the range l to r are the only set bits.
2. Calculate new_num = n & num.
3. If new_num == 0, return “Yes” (all bits are unset in the given range).
4. Else return “No” (all bits are not unset in the given range).
C++
458
Chapter 76. Check whether all the bits are unset in the given range or not
Java
459
Chapter 76. Check whether all the bits are unset in the given range or not
class GFG
{
// function to check whether
// all the bits are unset in
// the given range or not
static String allBitsSetInTheGivenRange(int n,
int l,
int r)
{
// calculating a number 'num'
// having 'r' number of bits
// and bits in the range l to
// r are the only set bits
int num = ((1 << r) - 1) ^
((1 << (l - 1)) - 1);
// new number which will
// only have one or more
// set bits in the range
// l to r and nowhere else
int new_num = n & num;
// if new num is 0, then
// all bits are unset in
// the given range
if(new_num == 0)
return "Yes";
// else all bits
// are not unset
return "No";
}
// Driver Code
public static void main (String[] args)
{
int n = 17;
int l = 2;
int r = 4;
System.out.println(
allBitsSetInTheGivenRange(n, l, r));
}
}
// This code is contributed by akt_mit
460
Chapter 76. Check whether all the bits are unset in the given range or not
PHP
<?php
// PHP implementation to check
// whether all the bits are
// unset in the given range
// or not
// function to check whether
// all the bits are unset in
// the given range or not
function allBitsSetInTheGivenRange($n,
$l, $r)
{
// calculating a number 'num'
// having 'r' number of bits
// and bits in the range l
// to r are the only set bits
$num = ((1 << $r) - 1) ^
((1 << ($l - 1)) - 1);
// new number which will
// only have one or more
// set bits in the range
// l to r and nowhere else
$new_num = $n & $num;
// if new num is 0, then
// all bits are unset in
// the given range
if ($new_num == 0)
return "Yes";
// else all bits
// are not unset
return "No";
}
// Driver Code
$n = 17;
$l = 2; $r = 4;
echo allBitsSetInTheGivenRange($n,
$l, $r);
// This code is contributed
// by ajit
?>
461
Chapter 76. Check whether all the bits are unset in the given range or not
Output:
Yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/check-whether-all-the-bits-are-unset-in-the-given-range-or-not/
462
Chapter 77
Check whether bits are in alternate pattern in the given range - GeeksforGeeks
Given a non-negative number n and two values l and r. The problem is to check whether
or not n has an alternate pattern in its binary representation in the range l to r. Here
alternate pattern means that the set and unset bits occur in alternate order. The bits are
numbered from right to left, i.e., the least significant bit is considered to be at first position.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Examples:
Input : n = 18, l = 1, r = 3
Output : Yes
(18)10 = (10010)2
The bits in the range 1 to 3 in the
binary representation of 18 are in
alternate order.
Input : n = 22, l = 2, r = 4
Output : No
(22)10 = (10110)2
The bits in the range 2 to 4 in the
binary representation of 22 are not in
alternate order.
Algorithm:
463
Chapter 77. Check whether bits are in alternate pattern in the given range
bitsAreInAltPatrnInGivenTRange(n, l, r)
prev = curr
num = num >> 1
return true;
C++
464
Chapter 77. Check whether bits are in alternate pattern in the given range
Java
465
Chapter 77. Check whether bits are in alternate pattern in the given range
466
Chapter 77. Check whether bits are in alternate pattern in the given range
int l = 1, r = 3;
if (bitsAreInAltPatrnInGivenTRange(n, l, r))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by mits
Python3
467
Chapter 77. Check whether bits are in alternate pattern in the given range
C#
// C# implementation to check
// whether bits are in alternate
// pattern in the given range
using System;
class GFG
{
// function to check whether
// bits are in alternate
// pattern in the given range
static bool bitsAreInAltPatrnInGivenTRange(int n,
int l, int r)
{
int num, prev, curr;
// right shift n by (l – 1) bits
num = n >> (l – 1);
// get the bit at the
// last position in ‘num’
prev = num & 1;
// right shift ‘num’ by 1
num = num >> 1;
// loop until there are
// bits in the given range
for (int i = 1; i <= (r - l); i++) { // get the bit at the // last position in ’num’ curr = num
468
Chapter 77. Check whether bits are in alternate pattern in the given range
& 1; // if true, then bits are // not in alternate pattern if (curr == prev) return false; //
update ’prev’ prev = curr; // right shift ’num’ by 1 num = num >> 1;
}
// bits are in alternate
// pattern in the given range
return true;
}
// Driver Code
static void Main()
{
int n = 18;
int l = 1, r = 3;
if (bitsAreInAltPatrnInGivenTRange(n, l, r))
Console.WriteLine(“Yes”);
else
Console.WriteLine(“No”);
}
}
// This code is contributed by mits
PHP
<?php
// PHP implementation to check
// whether bits are in alternate
// pattern in the given range
// function to check whether
// bits are in alternate
// pattern in the given range
function bitsAreInAltPatrnInGivenTRange($n, $l, $r)
{
// right shift n by (l - 1) bits
$num = $n >> ($l - 1);
// get the bit at the
// last position in 'num'
$prev = $num & 1;
// right shift 'num' by 1
$num = $num >> 1;
// loop until there are
// bits in the given range
for ($i = 1; $i <= ($r - $l); $i++)
469
Chapter 77. Check whether bits are in alternate pattern in the given range
{
// get the bit at the
// last position in 'num'
$curr = $num & 1;
// if true, then bits are
// not in alternate pattern
if ($curr == $prev)
return false;
// update 'prev'
$prev = $curr;
// right shift 'num' by 1
$num = $num >> 1;
}
// bits are in alternate
// pattern in the given range
return true;
}
// Driver Code
$n = 18;
$l = 1;
$r = 3;
if (bitsAreInAltPatrnInGivenTRange($n, $l, $r))
echo "Yes";
else
echo "No";
// This Code is contributed by mits
?>
Output:
Yes
Source
https://www.geeksforgeeks.org/check-whether-bits-are-in-alternate-pattern-in-the-given-range/
470
Chapter 78
Check whether bits are in alternate pattern in the given range | Set-2 - GeeksforGeeks
Given a non-negative number and two values and . The problem is to check
whether or not N has an alternate pattern in its binary representation in the range L to R.
Here, alternate pattern means that the set and unset bits occur in alternate order. The
bits are numbered from right to left, i.e., the least significant bit is considered to be at first
position.
Examples:
Input : N = 18, L = 1, R = 3
Output : Yes
(18)10 = (10010)2
The bits in the range 1 to 3 in the
binary representation of 18 are in
alternate order.
Input : N = 22, L = 2, R = 4
Output : No
(22)10 = (10110)2
The bits in the range 2 to 4 in the
binary representation of 22 are not in
alternate order.
Simple Approach: It has been discussed in this post which has a worst case time com-
plexity of O(log2 n).
471
Chapter 78. Check whether bits are in alternate pattern in the given range | Set-2
The entire idea of the above approach is to create a number num in which bits are in same
pattern as in the given range of n and then check whether bits are in alternate pattern in
num or not.
472
Chapter 78. Check whether bits are in alternate pattern in the given range | Set-2
return false;
}
// function to check if a number
// has bits in alternate pattern
bool bitsAreInAltOrder(unsigned int n)
{
unsigned int num = n ^ (n >> 1);
// to check if all bits are set
// in 'num'
return allBitsAreSet(num);
}
// function to check whether bits are in
// alternate pattern in the given range
bool bitsAreInAltPatrnInGivenRange(unsigned int n,
unsigned int l,
unsigned int r)
{
unsigned int num, left_shift;
// preparing a number 'num' and 'left_shift'
// which can be further used for the check
// of alternate pattern in the given range
if (isKthBitSet(n, r)) {
num = n;
left_shift = r;
}
else {
num = setKthBit(n, (r + 1));
left_shift = r + 1;
}
// unset all the bits which are left to the
// rth bit of (r+1)th bit
num = num & ((1 << left_shift) - 1);
// right shift 'num' by (l-1) bits
num = num >> (l - 1);
return bitsAreInAltOrder(num);
}
// Driver program to test above
int main()
{
unsigned int n = 18;
473
Chapter 78. Check whether bits are in alternate pattern in the given range | Set-2
unsigned int l = 1, r = 3;
if (bitsAreInAltPatrnInGivenRange(n, l, r))
cout << "Yes";
else
cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-whether-bits-are-in-alternate-pattern-in-the-given-range-set-2/
474
Chapter 79
Input : n = 10, k = 2
Output : Set
(10)10 = (1010)2
The 2nd bit from the right is set.
Input : n = 21, k = 4
Output : Unset
C++
475
Chapter 79. Check whether the bit at given position is set or unset
Java
// Java program to
// check the set bit
// at kth position
import java.io.*;
class GFG {
// function to check whether
// the bit at given position
// is set or unset
static int bitAtGivenPosSetOrUnset
( int n, int k)
{
// to shift the kth bit
// at 1st position
int new_num = n >> (k - 1);
// Since, last bit is now
// kth bit, so doing AND with 1
// will give result.
return (new_num & 1);
}
476
Chapter 79. Check whether the bit at given position is set or unset
Python3
C#
477
Chapter 79. Check whether the bit at given position is set or unset
// function to check whether
// the bit at given position
// is set or unset
static int bitAtGivenPosSetOrUnset(
int n, int k)
{
// to shift the kth bit
// at 1st position
int new_num = n >> (k - 1);
// Since, last bit is now
// kth bit, so doing AND with 1
// will give result.
return (new_num & 1);
}
// Driver code
public static void Main ()
{
// K and n must be greater
// than 0
int n = 10, k = 2;
if (bitAtGivenPosSetOrUnset(n, k)==1)
Console.Write("Set");
else
Console.Write("Unset");
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP implementation to check whether the bit
// at given position is set or unset
// function to check whether the bit
// at given position is set or unset
function bitAtGivenPosSetOrUnset($n, $k)
{
$new_num = $n >> ($k - 1);
// if it results to '1' then bit is set,
478
Chapter 79. Check whether the bit at given position is set or unset
Output:
Set
Source
https://www.geeksforgeeks.org/check-whether-bit-given-position-set-unset/
479
Chapter 80
Check whether the number has only first and last bits set - GeeksforGeeks
Given a positive integer n. The problem is to check whether only the first and last bits are
set in the binary representation of n.
Examples:
Input : 9
Output : Yes
(9)10 = (1001)2, only the first and
last bits are set.
Input : 15
Output : No
(15)10 = (1111)2, except first and last
there are other bits also which are set.
1. If n == 1, return “Yes”.
2. Else check whether n-1 is a power of 2. Refer this post.
C++
480
Chapter 80. Check whether the number has only first and last bits set
Java
481
Chapter 80. Check whether the number has only first and last bits set
// function to check whether the number has
// only first and last bits set
static boolean onlyFirstAndLastAreSet(int n)
{
if (n == 1)
return true;
return powerOfTwo(n-1);
}
// Driver program to test above
public static void main (String[] args) {
int n = Integer.parseUnsignedInt("9");
if (onlyFirstAndLastAreSet(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
/* This code is contributed by Mr. Somesh Awasthi */
Python3
482
Chapter 80. Check whether the number has only first and last bits set
else:
print('No')
# This code is contributed by Shariq Raza
C#
Output:
483
Chapter 80. Check whether the number has only first and last bits set
Yes
Source
https://www.geeksforgeeks.org/check-whether-number-first-last-bits-set/
484
Chapter 81
Check whether the number has only first and last bits set | Set 2 - GeeksforGeeks
Given a positive integer n, check whether only the first and last bits are set in the binary
representation of n. Print ‘Yes’ or ‘No’.
Examples:
Input: 9
Output: Yes
(9)10 = (1001)2, only the first and
last bits are set.
Input: 15
Output: No
(15)10 = (1111)2, except first and last
there are other bits also which are set.
485
Chapter 81. Check whether the number has only first and last bits set | Set 2
{
if (n == 1)
return true;
if (n == 2)
return false;
return (((n - 1) & (n - 2)) == 0);
}
// Driver program to test above
int main()
{
unsigned int n = 9;
if (onlyFirstAndLastAreSet(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
486
Chapter 81. Check whether the number has only first and last bits set | Set 2
System.out.println("No");
}
}
// This code is contributed
// by Smitha
Python3
C#
// C# to check whether
// the number has only
// first and last bits set
using System;
class GFG
{
// function to check whether
// the number has only
487
Chapter 81. Check whether the number has only first and last bits set | Set 2
PHP
<?php
// PHP to check whether the
// number has only first and
// last bits set
// function to check whether
// the number has only first
// and last bits set
function onlyFirstAndLastAreSet($n)
{
if ($n == 1)
return true;
if ($n == 2)
return false;
return ((($n - 1) &
($n - 2)) == 0);
}
// Driver Code
$n = 9;
if (onlyFirstAndLastAreSet($n))
488
Chapter 81. Check whether the number has only first and last bits set | Set 2
echo "Yes";
else
echo "No";
// This code is contributed
// by Smitha
?>
Output:
Yes
Source
https://www.geeksforgeeks.org/check-whether-the-number-has-only-first-and-last-bits-set-set-2/
489
Chapter 82
Check whether the two numbers differ at one bit position only - GeeksforGeeks
Given two non-negative integers a and b. The problem is to check whether the two numbers
differ at one bit position only or not.
Examples:
Input : a = 13, b = 9
Output : Yes
(13)10 = (1101)2
(9)10 = (1001)2
Both the numbers differ at one bit position only, i.e,
differ at the 3rd bit from the right.
Input : a = 15, b = 8
Output : No
1. Calculate num = a ^ b.
2. Check whether num is a power of 2 or not. Refer this post.
CPP
490
Chapter 82. Check whether the two numbers differ at one bit position only
// function to check if x is power of 2
bool isPowerOfTwo(unsigned int x)
{
// First x in the below expression is
// for the case when x is 0
return x && (!(x & (x - 1)));
}
// function to check whether the two numbers
// differ at one bit position only
bool differAtOneBitPos(unsigned int a,
unsigned int b)
{
return isPowerOfTwo(a ^ b);
}
// Driver program to test above
int main()
{
unsigned int a = 13, b = 9;
if (differAtOneBitPos(a, b))
cout << "Yes";
else
cout << "No";
return 0;
}
Python3
491
Chapter 82. Check whether the two numbers differ at one bit position only
if (differAtOneBitPos(a, b)):
print("Yes")
else:
print( "No")
# This code is contributed by "Sharad_Bhardwaj".
PHP
<?php
// PHP implementation to check
// whether the two numbers differ
// at one bit position only
// function to check if x is power of 2
function isPowerOfTwo($x)
{
$y = 0;
// First x in the below expression is
// for the case when x is 0
if($x && (!($x & ($x - 1))))
$y = 1;
return $y;
}
// function to check whether
// the two numbers differ at
// one bit position only
function differAtOneBitPos($a,$b)
{
return isPowerOfTwo($a ^ $b);
}
// Driver Code
$a = 13;
$b = 9;
if (differAtOneBitPos($a, $b))
echo "Yes";
else
echo "No";
// This code is contributed by Sam007
?>
Output:
492
Chapter 82. Check whether the two numbers differ at one bit position only
Yes
Source
https://www.geeksforgeeks.org/check-whether-two-numbers-differ-one-bit-position/
493
Chapter 83
Closest (or Next) smaller and greater numbers with same number of set bits - GeeksforGeeks
Given a positive integer n, print the next smallest and the previous largest number that
have the same number of 1 bits in their binary representation.
Examples :
Input : n = 5
Output : Closest Greater = 6
Closest Smaller = 3
Note that 5, 6 and 3 have same number of
set bits.
Input : n = 11
Output : Closest Greater = 13
Closest Smaller = 7
494
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
1 1 0 1 1 0 0 1 1 1 1 1 0 0
13 12 11 10 9 8 7 6 5 4 3 2 1 0
We want to make this number bigger (but not too big). We also need to keep the same
number of ones.
Observation: Given a number n and two bit locations i and j, suppose we flip bit i from a 1
to a 0, and bit j from a 0 to a 1. If i > j, then n will have decreased. If i < j, then n will
have increased.
We know the following:
To put this in a different way, we are flipping the rightmost non-trailing zero. That is, using
the above example, the trailing zeros are in the 0th and 1st spot. The rightmost non-trailing
zero is at bit 7. Let’s call this position p.
1 1 0 1 1 0 1 1 1 1 1 1 0 0
13 12 11 10 9 8 7 6 5 4 3 2 1 0
With this change, we have increased the number of 1s of n. We can shrink the number by
rearranging all the bits to the right of bit p such that the 0s are on the left and the 1s are
on the right. As we do this, we want to replace one of the 1s with a 0.
A relatively easy way of doing this is to count how many ones are to the right of p, clear all
the bits from 0 until p, and then add back in c1-1 ones. Let c1 be the number of ones to
the right of p and c0 be the number of zeros to the right of p.
Let’s walk through this with an example.
495
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
1 1 0 1 1 0 1 0 0 0 0 0 0 0
13 12 11 10 9 8 7 6 5 4 3 2 1 0
To clear these bits, we need to create a mask that is a sequence of ones, followed by p zeros.
We can do this as follows:
1 1 0 1 1 0 1 0 0 0 1 1 1 1
13 12 11 10 9 8 7 6 5 4 3 2 1 0
We have now arrived at the smallest number bigger than n with the same number of ones.
The Implementation of code for getNext is below
C++
496
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
497
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
Java
498
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
int p = c0 + c1;
// Flip rightmost
// non-trailing zero
n |= (1 << p);
// Clear all bits
// to the right of p
n &= ~((1 << p) - 1);
// Insert (c1-1) ones
// on the right.
n |= (1 << (c1 - 1)) - 1;
return n;
}
// Driver Code
public static void main (String[] args)
{
int n = 5; // input 1
System.out.println(getNext(n));
n = 8; // input 2
System.out.println(getNext(n));
}
}
// This code is contributed by aj_36
C#
499
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
int c1 = 0;
while (((c & 1) == 0) && (c != 0))
{
c0++;
c >>= 1;
}
while ((c & 1) == 1)
{
c1++;
c >>= 1;
}
// If there is no bigger number
// with the same no. of 1's
if (c0 + c1 == 31 || c0 + c1== 0)
return -1;
// position of rightmost
// non-trailing zero
int p = c0 + c1;
// Flip rightmost non-trailing
// zero
n |= (1 << p);
// Clear all bits to the right
// of p
n &= ~((1 << p) - 1);
// Insert (c1-1) ones on the
// right.
n |= (1 << (c1 - 1)) - 1;
return n;
}
// Driver Code
static void Main()
{
int n = 5; // input 1
Console.WriteLine(getNext(n));
n = 8; // input 2
Console.Write(getNext(n));
}
}
500
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
// This code is contributed by Anuj_67
PHP
<?php
// PHP implementation of getNext with
// same number of bits 1's is below
// Function to find next smallest
// number bigger than n
function getNext($n)
{
// Compute c0 and c1
$c = $n;
$c0 = 0;
$c1 = 0;
while ((($c & 1) == 0) &&
($c != 0))
{
$c0 ++;
$c >>= 1;
}
while (($c & 1) == 1)
{
$c1++;
$c >>= 1;
}
// If there is no bigger
// number with the
// same no. of 1's
if ($c0 + $c1 == 31 ||
$c0 + $c1== 0)
return -1;
// position of rightmost
// non-trailing zero
$p = $c0 + $c1;
// Flip rightmost non -
// trailing zero
$n |= (1 << $p);
// Clear all bits to
// the right of p
501
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
Output:
6
16
• Compute c0 and c1. Note that c1 is the number of trailing ones, and c0 is the size of
the block of zeros immediately to the left of the trailing ones.
• Flip the rightmost non-trailing one to a zero. This will be at position p = c1 + c0.
• Clear all bits to the right of bit p.
• Insert c1 + 1 ones immediately to the right of position p.
Note that Step 2 sets bit p to a zero and Step 3 sets bits 0 through p-1 to a zero. We can
merge these steps.
Let’s walk through this with an example.
502
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
1 0 0 1 1 1 1 0 0 0 0 0 1 1
13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 0 0 1 1 1 0 0 0 0 0 0 0 0
13 12 11 10 9 8 7 6 5 4 3 2 1 0
// Sequence of 1s
int a = ~0;
1 0 0 1 1 1 0 1 1 1 0 0 0 0
13 12 11 10 9 8 7 6 5 4 3 2 1 0
Note that since p =c1 + c0, then (c1 + 1) ones will be followed by (c0 – 1)zeros.
We can do this as follows:
// 0s followed by c1 + 1 ones
int b = a - 1;
503
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
C++
504
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
int main()
{
int n = 6; // input 1
cout << getPrev(n);
n = 16; // input 2
cout << endl;
cout << getPrev(n);
return 0;
}
Java
505
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
// position of rightmost
// non-trailing one.
int p = c0 + c1;
// clears from bit p onwards
n = n & ((~0) << (p + 1));
// Sequence of (c1+1) ones
int mask = (1 << (c1 + 1)) - 1;
n = n | mask << (c0 - 1);
return n;
}
// Driver Code
public static void main(String[] args)
{
int n = 6; // input 1
System.out.println(getPrev(n));
n = 16; // input 2
System.out.println(getPrev(n));
}
}
// This code is contributed by aj_36
C#
// C# Implementation of
// getPrev in Same number
// of bits 1's is below
using System;
class GFG
{
// Main Function to find
// next Bigger number
// Smaller than n
static int getPrev(int n)
{
// Compute c0 and
// c1 and store N
int temp = n;
int c0 = 0;
506
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
int c1 = 0;
while((temp & 1) == 1)
{
c1++;
temp = temp >> 1;
}
if(temp == 0)
return -1;
while(((temp & 1) == 0) &&
(temp != 0))
{
c0++;
temp = temp >> 1;
}
// position of rightmost
// non-trailing one.
int p = c0 + c1;
// clears from
// bit p onwards
n = n & ((~0) << (p + 1));
// Sequence of
// (c1+1) ones
int mask = (1 << (c1 + 1)) - 1;
n = n | mask << (c0 - 1);
return n;
}
// Driver Code
static public void Main ()
{
int n = 6; // input 1
Console.WriteLine(getPrev(n));
n = 16; // input 2
Console.WriteLine(getPrev(n));
}
}
// This code is contributed by ajit
507
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
PHP
<?php
// PHP Implementation of getPrev in
// Same number of bits 1's is below
// Main Function to find next Bigger
// number Smaller than n
function getPrev($n)
{
// Compute c0 and
// c1 and store N
$temp = $n;
$c0 = 0;
$c1= 0;
while (($temp & 1) == 1)
{
$c1++;
$temp = $temp >> 1;
}
if ($temp == 0)
return -1;
while ((($temp & 1) == 0) &&
($temp!= 0))
{
$c0++;
$temp = $temp >> 1;
}
// position of rightmost
// non-trailing one.
$p = $c0 + $c1;
// clears from bit p onwards
$n = $n & ((~0) << ($p + 1));
// Sequence of (c1 + 1) ones
$mask = (1 << ($c1 + 1)) - 1;
$n = $n | $mask << ($c0 - 1);
return $n;
}
508
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
// Driver Code
// input 1
$n = 6;
echo getPrev($n);
// input 2
$n = 16;
echo " \n" ;
echo getPrev($n);
// This code is contributed by Ajit
?>
Output :
5
8
A quick way to perform steps 1 and 2 is to set the trailing zeros to 1 (giving us p trailing
ones), and then add 1. Adding one will flip all trailing ones, so we wind up with a 1 at bit
p followed by p zeros. We can perform this arithmetically.
// Sets trailing 0s to 1, giving us p trailing 1s.
n += 2c0 – 1 ;
// Flips first p ls to 0s, and puts a 1 at bit p.
n += 1;
Now, to perform Step 3 arithmetically, we just do:
// Sets trailing c1 – 1 zeros to ones.
n += 2c1 – 1 – 1;
This math reduces to:
next = n + (2c0 – 1) + 1 + (2c1 – 1 – 1)
= n + 2c0 + 2c1 – 1 – 1
The best part is that, using a little bit manipulation, it’s simple to code.
C++
509
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
Java
510
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
511
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
C#
// C# Implementation of getNext
// with Same number of bits
// 1's is below
using System;
class GFG
{
// Function to find next smallest
// number bigger than n
static int getNext(int n)
{
/* Compute c0
and c1 */
int c = n;
int c0 = 0;
int c1 = 0;
while (((c & 1) == 0) &&
(c != 0))
{
c0 ++;
c >>= 1;
}
while ((c & 1) == 1)
{
c1++;
c >>= 1;
}
// If there is no bigger
// number with the same
// no. of 1's
if (c0 + c1 == 31 ||
c0 + c1 == 0)
return -1;
return n + (1 << c0) +
(1 << (c1 - 1)) - 1;
}
// Driver Code
static public void Main ()
{
int n = 5; // input 1
Console.WriteLine(getNext(n));
512
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
n = 8; // input 2
Console.WriteLine(getNext(n));
}
}
// This code is contributed by m_kit
PHP
<?php
// PHP Implementation of
// getNext with Same number
// of bits 1's is below
// Main Function to find
// next smallest number
// bigger than n
function getNext($n)
{
/* Compute c0 and c1 */
$c = $n;
$c0 = 0;
$c1 = 0;
while ((($c & 1) == 0) &&
($c != 0))
{
$c0 ++;
$c >>= 1;
}
while (($c & 1) == 1)
{
$c1++;
$c >>= 1;
}
// If there is no bigger
// number with the
// same no. of 1's
if ($c0 + $c1 == 31 ||
$c0 + $c1 == 0)
return -1;
return $n + (1 << $c0) +
(1 << ($c1 - 1)) - 1;
}
513
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
// Driver Code
$n = 5; // input 1
echo getNext($n);
$n = 8; // input 2
echo "\n";
echo getNext($n);
// This code is contributed by ajit
?>
Output :
6
16
We can implement this arithmetically as follows. For clarity in the example, we assume n
= 10000011. This makes c1 = 2 and c0 = 5.
514
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
Java
515
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
516
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
}
// This code is contributed by akt_mit
C#
// C# Implementation of Arithmetic
// Approach to getPrev with Same
// number of bits 1's is below
using System;
class GFG
{
// Main Function to find next
// Bigger number Smaller than n
static int getPrev(int n)
{
/* Compute c0 and
c1 and store N*/
int temp = n;
int c0 = 0;
int c1 = 0;
while ((temp & 1) == 1)
{
c1++;
temp = temp >> 1;
}
if (temp == 0)
return -1;
while (((temp & 1) == 0) &&
(temp!= 0))
{
c0++;
temp = temp >> 1;
}
return n - (1 << c1) -
(1 << (c0 - 1)) + 1;
}
// Driver Code
static public void Main ()
{
int n = 6; // input 1
517
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
Console.WriteLine(getPrev(n));
n = 16; // input 2
Console.WriteLine(getPrev(n));
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to count of
// steps until one of the
// two numbers become 0.
// Returns count of steps
// before one of the numbers
// become 0 after repeated
// subtractions.
function countSteps($x, $y)
{
// If y divides x, then
// simply return x/y.
if ($x % $y == 0)
return floor(((int)$x / $y));
// Else recur. Note that this
// function works even if x is
// smaller than y because in that
// case first recursive call
// exchanges roles of x and y.
return floor(((int)$x / $y) +
countSteps($y, $x % $y));
}
// Driver code
$x = 100;
$y = 19;
echo countSteps($x, $y);
// This code is contributed by aj_36
?>
Output :
518
Chapter 83. Closest (or Next) smaller and greater numbers with same number of set bits
5
8
Source
https://www.geeksforgeeks.org/closest-next-smaller-greater-numbers-number-set-bits/
519
Chapter 84
Input : A = 5 , B = 6
Output : 0
Input : A = 5 , B = 5
Output : 1
idea is pretty simple we do Xor of both element ( A , B ) . if Xor is zero then two number
are equal else not .
Below is the implementation of above idea :
C++
520
Chapter 84. Compare two integers without using any Comparison operator
{
return ( A ^ B ) ;
}
// Driver program
int main()
{
int A = 5 , B = 6;
cout << !EqualNumber(A, B) << endl;
return 0;
}
Python3
Output:
Reference :http://stackoverflow.com/questions/476800/comparing-two-integers-without-any-comparison
Source
https://www.geeksforgeeks.org/compare-two-integers-without-using-comparison-operator/
521
Chapter 85
C++
#include<stdio.h>
// This function will return n % d.
// d must be one of: 1, 2, 4, 8, 16, 32, …
unsigned int getModulo(unsigned int n,
unsigned int d)
{
return ( n & (d - 1) );
}
// Driver Code
int main()
{
522
Chapter 85. Compute modulus division by a power-of-2-number
unsigned int n = 6;
// d must be a power of 2
unsigned int d = 4;
printf("%u moduo %u is %u", n, d, getModulo(n, d));
getchar();
return 0;
}
Java
Python3
523
Chapter 85. Compute modulus division by a power-of-2-number
C#
PHP
524
Chapter 85. Compute modulus division by a power-of-2-number
<?php
// This function will return n % d.
// d must be one of: 1, 2, 4, 8, 16, 32, …
function getModulo($n, $d)
{
return ( $n & ($d - 1) );
}
// Driver Code
$n = 6;
// d must be a power of 2
$d = 4;
echo $n ," moduo"," ", $d, " is ",
" ",getModulo($n, $d);
// This code is contributed by vt_m.
?>
References:
http://graphics.stanford.edu/~seander/bithacks.html#ModulusDivisionEasy
Improved By : vt_m
Source
https://www.geeksforgeeks.org/compute-modulus-division-by-a-power-of-2-number/
525
Chapter 86
mask = n>>31
mask + n
(mask + n)^mask
Implementation:
526
Chapter 86. Compute the integer absolute value (abs) without branching
#include <stdio.h>
#define CHAR_BIT 8
/* This function will return absoulte value of n*/
unsigned int getAbs(int n)
{
int const mask = n >> (sizeof(int) * CHAR_BIT - 1);
return ((n + mask) ^ mask);
}
/* Driver program to test above function */
int main()
{
int n = -6;
printf("Absoute value of %d is %u", n, getAbs(n));
getchar();
return 0;
}
Method 2:
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
mask ^ n
(mask^n) - mask
Implementation:
On machines where branching is expensive, the above expression can be faster than the
obvious approach, r = (v < 0) ? -(unsigned)v : v, even though the number of operations is
the same. Please see thisfor more details about the above two methods.
References:
http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs
527
Chapter 86. Compute the integer absolute value (abs) without branching
Source
https://www.geeksforgeeks.org/compute-the-integer-absolute-value-abs-without-branching/
528
Chapter 87
Below are the methods to get minimum(or maximum) without using branching. Typically,
the obvious approach is best, though.
Method 1(Use XOR and comparison operator)
Minimum of x and y will be
It works because if x < y, then -(x = y, then -(x < y) will be all zeros, so r = y ^ ((x ^ y)
& 0) = y. On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so
there may be no advantage.
To find the maximum, use
529
Chapter 87. Compute the minimum or maximum of two integers without branching
#include<stdio.h>
/*Function to find minimum of x and y*/
int min(int x, int y)
{
return y ^ ((x ^ y) & -(x < y));
}
/*Function to find maximum of x and y*/
int max(int x, int y)
{
return x ^ ((x ^ y) & -(x < y));
}
/* Driver program to test above functions */
int main()
{
int x = 15;
int y = 6;
printf("Minimum of %d and %d is ", x, y);
printf("%d", min(x, y));
printf("\nMaximum of %d and %d is ", x, y);
printf("%d", max(x, y));
getchar();
}
Python3
530
Chapter 87. Compute the minimum or maximum of two integers without branching
print(min(x, y))
print("Maximum of", x, "and", y, "is", end=" ")
print(max(x, y))
# This code is contributed
# by Smitha Dinesh Semwal
PHP
<?php
// PHP program to Compute the minimum
// or maximum of two integers without
// branching
// Function to find minimum
// of x and y
function m_in($x, $y)
{
return $y ^ (($x ^ $y) &
- ($x < $y));
}
// Function to find maximum
// of x and y
function m_ax($x, $y)
{
return $x ^ (($x ^ $y) &
- ($x < $y));
}
// Driver Code
$x = 15;
$y = 6;
echo"Minimum of"," ", $x," ","and",
" ",$y," "," is "," ";
echo m_in($x, $y);
echo "\nMaximum of"," ",$x," ",
"and"," ",$y," ", " is ";
echo m_ax($x, $y);
// This code is contributed by anuj_67.
?>
531
Chapter 87. Compute the minimum or maximum of two integers without branching
Output:
Minimum of 15 and 6 is 6
Maximum of 15 and 6 is 15
, then we can use the following, which are faster because (x – y) only needs to be evaluated
once.
Minimum of x and y will be
This method shifts the subtraction of x and y by 31 (if size of integer is 32). If (x-y) is
smaller than 0, then (x -y)>>31 will be 1. If (x-y) is greater than or equal to 0, then (x
-y)>>31 will be 0.
So if x >= y, we get minimum as y + (x-y)&0 which is y.
If x < y, we get minimum as y + (x-y)&1 which is x.
Similarly, to find the maximum use
#include<stdio.h>
#define CHAR_BIT 8
/*Function to find minimum of x and y*/
int min(int x, int y)
{
return y + ((x - y) & ((x - y) >>
(sizeof(int) * CHAR_BIT - 1)));
}
/*Function to find maximum of x and y*/
int max(int x, int y)
{
return x - ((x - y) & ((x - y) >>
(sizeof(int) * CHAR_BIT - 1)));
}
/* Driver program to test above functions */
int main()
{
532
Chapter 87. Compute the minimum or maximum of two integers without branching
int x = 15;
int y = 6;
printf("Minimum of %d and %d is ", x, y);
printf("%d", min(x, y));
printf("\nMaximum of %d and %d is ", x, y);
printf("%d", max(x, y));
getchar();
}
Note that the 1989 ANSI C specification doesn’t specify the result of signed right-shift, so
above method is not portable. If exceptions are thrown on overflows, then the values of x
and y should be unsigned or cast to unsigned for the subtractions to avoid unnecessarily
throwing an exception, however the right-shift needs a signed operand to produce all one
bits when negative, so cast to signed there.
Source:
http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
Improved By : vt_m
Source
https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/
533
Chapter 88
Compute the parity of a number using XOR and table look-up - GeeksforGeeks
Parity of a number refers to whether it contains an odd or even number of 1-bits. The
number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it
contains even number of 1-bits.
Examples:
Input : 254
Output : Odd Parity
Explanation : Binary of 254 is 11111110.
There are 7 ones. Thus, parity is odd.
Input : 1742346774
Output : Even
534
Chapter 88. Compute the parity of a number using XOR and table look-up
1. If S1 and S2 have the same parity, i.e. they both have an even number of bits or an
odd number of bits, their union S will have an even number of bits.
2. Therefore parity of S is XOR of parities of S1 and S2
The idea is to create a look up table to store parities of all 8 bit numbers. Then compute
parity of whole number by dividing it into 8 bit numbers and using above facts.
Steps:
Since a 32 bit or 64 bit number contains constant number of bytes, the above steps take
O(1) time.
Example :
4. Compute X-OR :
0110011111011010
^ 0001101000010110
___________________
= 0111110111001100
535
Chapter 88. Compute the parity of a number using XOR and table look-up
^ 11001100
___________________
= 10110001
10110001 is 177 in decimal. Check
for its parity in look-up table :
Even number of 1 = Even parity.
Below is the implementation that works for both 32 bit and 64 bit numbers.
C++
536
Chapter 88. Compute the parity of a number using XOR and table look-up
// Result is 1 for odd parity, 0 for even parity
bool result = Parity(num);
// Printing the desired result
result ? std::cout << "Odd Parity" :
std::cout << "Even Parity";
return 0;
}
PHP
<?php
// PHP program to illustrate
// Compute the parity of a
// number using XOR
/* Generating the look-up
table while pre-processing
#define P2(n) n, n ^ 1, n ^ 1, n
#define P4(n) P2(n), P2(n ^ 1),
P2(n ^ 1), P2(n)
#define P6(n) P4(n), P4(n ^ 1),
P4(n ^ 1), P4(n)
#define LOOK_UP P6(0), P6(1),
P6(1), P6(0)
LOOK_UP is the macro expansion
to generate the table
$table = array(LOOK_UP );
*/
// Function to find
// the parity
function Parity($num)
{
global $table;
// Number is considered
// to be of 32 bits
$max = 16;
// Dividing the number
// into 8-bit chunks
// while performing X-OR
while ($max >= 8)
{
537
Chapter 88. Compute the parity of a number using XOR and table look-up
Output:
Even Parity
Time Complexity : O(1). Note that a 32 bit or 64 bit number has fixed number of bytes
(4 in case of 32 bits and 8 in case of 64 bits).
Improved By : jit_t
Source
https://www.geeksforgeeks.org/compute-parity-number-using-xor-table-look/
538
Chapter 89
• We compute the NOT of 0 to get a number with 32 1s. This number is not equal to
INT_MAX because the sign bit is 1, i.e. negative number.
• Now, a right shift of this number will produce 011…111 which is INT_MAX.
• INT_MIN is NOT of INT_MAX.
Note :
0 should be taken as unsigned int.
Reason :
If 0 is signed, during Step 2, right shift of 111..111 will yield 111…111. This is because
arithmetic right shift preserves the sign of the number.
In Java, we have the feature of logical right shift available to us.
C/C++
539
Chapter 89. Computing INT_MAX and INT_MIN with Bitwise operations
Java
540
Chapter 89. Computing INT_MAX and INT_MIN with Bitwise operations
Output:
Asked in : Google
Source
https://www.geeksforgeeks.org/computing-int_max-int_min-bitwise-operations/
541
Chapter 90
Construct an array from XOR of all elements of array except element at same index -
GeeksforGeeks
Given an array A[] having n positive elements. The task to create another array B[] such as
B[i] is XOR of all elements of array A[] except A[i].
Examples :
Naive Approach :
We can simple calculate B[i] as XOR of all elements of A[] except A[i], as
542
Chapter 90. Construct an array from XOR of all elements of array except element at
same index
Optimized Approach :
First calculate XOR of all elements of array A[] say ’xor’, and for each element of array A[]
calculate A[i] = xor ^ A[i] .
int xor = 0;
for (int i = 0; i < n; i++)
xor ^= A[i];
C++
543
Chapter 90. Construct an array from XOR of all elements of array except element at
same index
Java
Python3
544
Chapter 90. Construct an array from XOR of all elements of array except element at
same index
C#
545
Chapter 90. Construct an array from XOR of all elements of array except element at
same index
{
int []A = { 2, 4, 1, 3, 5};
int n = A.Length;
constructXOR(A, n);
// print result
for (int i = 0; i < n; i++)
Console.Write(A[i] + " ");
}
}
// This code is contributed by nitin mittal
Output:
3 5 0 2 4
Related Problem :
A Product Array Puzzle
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/construct-an-array-from-xor-of-all-elements-of-array-except-element-at-same-index
546
Chapter 91
Input : 110001110
Output : 616
Input : 1111001010010100001.010110110011011
Output : 1712241.26633
The idea is to consider the binary input as a string of characters and then follow the steps:
1. Get length of substring to the left and right of the decimal point(‘.’) as left_len and
right_len.
2. If left_len is not a multiple of 3 add min number of 0’s in the beginning to make
length of left substring a multiple of 3.
3. If right_len is not a multiple of 3 add min number of 0’s in the end to make length
of right substring a multiple of 3.
4. Now, from the left extract one by one substrings of length 3 and add its corresponding
octal code to the result.
5. If in between a decimal(‘.’) is encountered then add it to the result.
547
Chapter 91. Convert a binary number to octal
#include <bits/stdc++.h>
using namespace std;
// function to create map between binary
// number and its equivalent octal
void createMap(unordered_map<string, char> *um)
{
(*um)["000"] = '0';
(*um)["001"] = '1';
(*um)["010"] = '2';
(*um)["011"] = '3';
(*um)["100"] = '4';
(*um)["101"] = '5';
(*um)["110"] = '6';
(*um)["111"] = '7';
}
// Function to find octal equivalent of binary
string convertBinToOct(string bin)
{
int l = bin.size();
int t = bin.find_first_of('.');
// length of string before '.'
int len_left = t != -1 ? t : l;
// add min 0's in the beginning to make
// left substring length divisible by 3
for (int i = 1; i <= (3 - len_left % 3) % 3; i++)
bin = '0' + bin;
// if decimal point exists
if (t != -1)
{
// length of string after '.'
int len_right = l - len_left - 1;
// add min 0's in the end to make right
// substring length divisible by 3
for (int i = 1; i <= (3 - len_right % 3) % 3; i++)
bin = bin + '0';
}
// create map between binary and its
// equivalent octal code
unordered_map<string, char> bin_oct_map;
createMap(&bin_oct_map);
548
Chapter 91. Convert a binary number to octal
int i = 0;
string octal = "";
while (1)
{
// one by one extract from left, substring
// of size 3 and add its octal code
octal += bin_oct_map[bin.substr(i, 3)];
i += 3;
if (i == bin.size())
break;
// if '.' is encountered add it to result
if (bin.at(i) == '.')
{
octal += '.';
i++;
}
}
// required octal number
return octal;
}
// Driver program to test above
int main()
{
string bin = "1111001010010100001.010110110011011";
cout << "Octal number = "
<< convertBinToOct(bin);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/convert-binary-number-octal/
549
Chapter 92
Input: n = 2.47, k = 5
Output: 10.01111
Input: n = 6.986 k = 8
Output: 110.11111100
We strongly recommend that you click here and practice it, before moving on to the solution.
A) Convert the integral part of decimal to binary equivalent
550
Chapter 92. Convert decimal fraction to binary number
551
Chapter 92. Convert decimal fraction to binary number
binary.push_back(rem +'0');
Integral /= 2;
}
// Reverse string to get original binary
// equivalent
reverse(binary.begin(),binary.end());
// Append point before conversion of
// fractional part
binary.push_back('.');
// Conversion of fractional part to
// binary equivalent
while (k_prec--)
{
// Find next bit in fraction
fractional *= 2;
int fract_bit = fractional;
if (fract_bit == 1)
{
fractional -= fract_bit;
binary.push_back(1 + '0');
}
else
binary.push_back(0 + '0');
}
return binary;
}
// Driver code
int main()
{
double n = 4.47;
int k = 3;
cout << decimalToBinary(n, k) << "\n";
n = 6.986 , k = 5;
cout << decimalToBinary(n, k);
return 0;
}
Output:
552
Chapter 92. Convert decimal fraction to binary number
100.011
110.11111
Source
https://www.geeksforgeeks.org/convert-decimal-fraction-binary-number/
553
Chapter 93
Input : x = 8, y = 7, l = 1, r = 2
Output : x = 11
554
Chapter 93. Copy set bits in a range
// by this function.
void copySetBits(unsigned &x, unsigned y,
unsigned l, unsigned r)
{
// l and r must be between 1 to 32
// (assuming ints are stored using
// 32 bits)
if (l < 1 || r > 32)
return ;
// Travers in given range
for (int i=l; i<=r; i++)
{
// Find a mask (A number whose
// only set bit is at i'th position)
int mask = 1 << (i-1);
// If i'th bit is set in y, set i'th
// bit in x also.
if (y & mask)
x = x | mask;
}
}
// Driver code
int main()
{
unsigned x = 10, y = 13, l = 2, r = 3;
copySetBits(x, y, l, r);
cout << "Modified x is " << x;
return 0;
}
Output :
Modified x is 14
555
Chapter 93. Copy set bits in a range
// by this function.
void copySetBits(unsigned &x, unsigned y,
unsigned l, unsigned r)
{
// l and r must be between 1 to 32
if (l < 1 || r > 32)
return ;
// get the length of the mask
int maskLength = (1<<(r-l+1)) - 1;
// Shift the mask to the required position
// "&" with y to get the set bits at between
// l ad r in y
int mask = ((maskLength)<<(l-1)) & y ;
x = x | mask;
}
// Driver code
int main()
{
unsigned x = 10, y = 13, l = 2, r = 3;
copySetBits(x, y, l, r);
cout << "Modified x is " << x;
return 0;
}
Output :
Modified x is 14
Source
https://www.geeksforgeeks.org/copy-set-bits-in-a-range/
556
Chapter 94
We strongly recommend that you click here and practice it, before moving on to the solution.
Naive Approach
A brute force is to run the two loops one inside the another and select the pairs one by one
and take a XOR of both elements. The result of XORed value contains a set bits which are
differ in both the elements. Now we just need to count total set bits so that we compare it
with value K.
C++
557
Chapter 94. Count all pairs of an array which differ in K bits
558
Chapter 94. Count all pairs of an array which differ in K bits
PHP
<?php
// PHP program to count all
// pairs with bit difference
// as k
// Utility function to count
// total ones in a number
function bitCount($n)
{
$count = 0;
while ($n)
{
if ($n & 1)
++$count;
$n >>= 1;
}
return $count;
}
// Function to count pairs
// of K different bits
function countPairsWithKDiff($arr, $n, $k)
{
// initialize final answer
$ans = 0;
for ($i = 0; $i < $n-1; ++$i)
{
for ($j = $i + 1; $j < $n; ++$j)
{
$xoredNum = $arr[$i] ^ $arr[$j];
// Check for K differ bit
if ($k == bitCount($xoredNum))
++$ans;
}
}
return $ans;
}
// Driver code
$k = 2;
$arr = array(2, 4, 1, 3, 1);
559
Chapter 94. Count all pairs of an array which differ in K bits
$n = count($arr);
echo "Total pairs for k = " , $k , " are = "
, countPairsWithKDiff($arr, $n, $k) , "\n";
// This code is contributed by anuj_67.
?>
Time complexity: O(N2 * log MAX) where MAX is maximum element in input array.
Auxiliary space: O(1)
Efficient approach
This approach is efficient for the cases when input array has small elements and possibly
many repetitions. The idea is to iterate from 0 to max(arr[i]) and for every pair(i, j) check
the number of set bits in (i ^ j) and compare this with K. We can use inbuilt function of
gcc( __builtin_popcount ) or precompute such array to make the check faster. If number
of ones in i ^ j is equals to K then we will add the total count of both i and j.
560
Chapter 94. Count all pairs of an array which differ in K bits
if (k == 0)
{
for (int i = 0; i <= MAX; ++i)
ans += (count[i] * (count[i] - 1)) / 2;
return ans;
}
for (int i = 0; i <= MAX; ++i)
{
// if count[i] is 0, skip the next loop as it
// will not contribute the answer
if (!count[i])
continue;
for (int j = i + 1; j <= MAX; ++j)
{
//Update answer if k differ bit found
if ( __builtin_popcount(i ^ j) == k)
ans += count[i] * count[j];
}
}
return ans;
}
// Driver code
int main()
{
int k = 2;
int arr[] = {2, 4, 1, 3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Total pairs for k = " << k << " are = "
<< kBitDifferencePairs(arr, n, k) << "\n";
k = 3;
cout << "Total pairs for k = " << k << " are = "
<< kBitDifferencePairs(arr, n, k) ;
return 0;
}
561
Chapter 94. Count all pairs of an array which differ in K bits
Source
https://www.geeksforgeeks.org/count-all-pairs-of-an-array-which-differ-in-k-bits/
562
Chapter 95
A Simple solution is to traverse each element and check if there’s another number whose
XOR with it is equal to x. This solution takes O(n2 ) time.
An efficient solution of this problem take O(n) time. The idea is based on the fact that
arr[i] ^ arr[j] is equal to x if and only if arr[i] ^ x is equal to arr[j].
1) Initialize result as 0.
2) Create an empty hash set "s".
3) Do following for each element arr[i] in arr[]
(a) If x ^ arr[i] is in "s", then increment result by 1.
(b) Insert arr[i] into the hash set "s".
3) return result.
C++
563
Chapter 95. Count all pairs with given XOR
Python3
564
Chapter 95. Count all pairs with given XOR
Output:
C++
565
Chapter 95. Count all pairs with given XOR
// value x
#include<bits/stdc++.h>
using namespace std;
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
unordered_map<int, int> m;
for (int i=0; i<n ; i++)
{
int curr_xor = x^arr[i];
// If there exist an element in map m
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (m.find(curr_xor) != m.end())
result += m[curr_xor];
// Increment count of current element
m[arr[i]]++;
}
// return total count of pairs with XOR equal to x
return result;
}
// driver program
int main()
{
int arr[] = {2, 5, 2};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 0;
cout << "Count of pairs with given XOR = "
<< xorPairCount(arr, n, x);
return 0;
}
Output:
566
Chapter 95. Count all pairs with given XOR
Source
https://www.geeksforgeeks.org/count-pairs-given-xor/
567
Chapter 96
Example:
Input: arr[] = {8, 4, 2, 1}
Output: 6
Given array has six inversions (8,4), (4,2),
(8,2), (8,1), (4,1), (2,1).
BIT is implemented using an array and works in form of trees. Note that there are two
ways of looking at BIT as a tree.
568
Chapter 96. Count inversions in an array | Set 3 (Using BIT)
We recommend you to refer Binary Indexed Tree (BIT) before further reading this post.
Basic Approach using BIT of size Θ(maxElement):
The idea is to iterate the array from n-1 to 0. When we are at i’th index, we check how
many numbers less than arr[i] are present in BIT and add it to the result. To get the count
of smaller elements, getSum() of BIT is used. In his basic idea, BIT is represented as an
array of size equal to maximum element plus one. So that elements can be used as an index.
After that we add current element to to the BIT[] by doing an update operation that updates
count of current element from 0 to 1, and therefore updates ancestors of current element in
BIT (See update() in BIT for details).
Below is C++ implementation of basic idea that uses BIT.
569
Chapter 96. Count inversions in an array | Set 3 (Using BIT)
// Update index to that of parent in update View
index += index & (-index);
}
}
// Returns inversion count arr[0..n-1]
int getInvCount(int arr[], int n)
{
int invcount = 0; // Initialize result
// Find maximum element in arr[]
int maxElement = 0;
for (int i=0; i<n; i++)
if (maxElement < arr[i])
maxElement = arr[i];
// Create a BIT with size equal to maxElement+1 (Extra
// one is used so that elements can be directly be
// used as index)
int BIT[maxElement+1];
for (int i=1; i<=maxElement; i++)
BIT[i] = 0;
// Traverse all elements from right.
for (int i=n-1; i>=0; i--)
{
// Get count of elements smaller than arr[i]
invcount += getSum(BIT, arr[i]-1);
// Add current element to BIT
updateBIT(BIT, maxElement, arr[i], 1);
}
return invcount;
}
// Driver program
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof(arr)/sizeof(int);
cout << "Number of inversions are : " << getInvCount(arr,n);
return 0;
}
Output:
570
Chapter 96. Count inversions in an array | Set 3 (Using BIT)
Time Complexity :- The update function and getSum function runs for O(log(maximumelement))
and we are iterating over n elements. So overall time complexity is : O(nlog(maximumelement)).
Auxiliary space : O(maxElement)
Better Approach using BIT of size Θ(n):
The problem with the previous approach is that it doesn’t work for negative numbers as
index cannot be negative. Also by updating the value till maximum element we waste time
and space as it is quite possible that we may never use intermediate value. For example,
lots of space an time is wasted for an array like {1, 100000}.
The idea is to convert given array to an array with values from 1 to n and relative order of
smaller and greater elements remains
Example :-
arr[] = {7, -90, 100, 1}
571
Chapter 96. Count inversions in an array | Set 3 (Using BIT)
}
// Updates a node in Binary Index Tree (BITree) at given index
// in BITree. The given value 'val' is added to BITree[i] and
// all of its ancestors in tree.
void updateBIT(int BITree[], int n, int index, int val)
{
// Traverse all ancestors and add 'val'
while (index <= n)
{
// Add 'val' to current node of BI Tree
BITree[index] += val;
// Update index to that of parent in update View
index += index & (-index);
}
}
// Converts an array to an array with values from 1 to n
// and relative order of smaller and greater elements remains
// same. For example, {7, -90, 100, 1} is converted to
// {3, 1, 4 ,2 }
void convert(int arr[], int n)
{
// Create a copy of arrp[] in temp and sort the temp array
// in increasing order
int temp[n];
for (int i=0; i<n; i++)
temp[i] = arr[i];
sort(temp, temp+n);
// Traverse all array elements
for (int i=0; i<n; i++)
{
// lower_bound() Returns pointer to the first element
// greater than or equal to arr[i]
arr[i] = lower_bound(temp, temp+n, arr[i]) - temp + 1;
}
}
// Returns inversion count arr[0..n-1]
int getInvCount(int arr[], int n)
{
int invcount = 0; // Initialize result
// Convert arr[] to an array with values from 1 to n and
// relative order of smaller and greater elements remains
// same. For example, {7, -90, 100, 1} is converted to
572
Chapter 96. Count inversions in an array | Set 3 (Using BIT)
// {3, 1, 4 ,2 }
convert(arr, n);
// Create a BIT with size equal to maxElement+1 (Extra
// one is used so that elements can be directly be
// used as index)
int BIT[n+1];
for (int i=1; i<=n; i++)
BIT[i] = 0;
// Traverse all elements from right.
for (int i=n-1; i>=0; i--)
{
// Get count of elements smaller than arr[i]
invcount += getSum(BIT, arr[i]-1);
// Add current element to BIT
updateBIT(BIT, n, arr[i], 1);
}
return invcount;
}
// Driver program
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof(arr)/sizeof(int);
cout << "Number of inversions are : " << getInvCount(arr,n);
return 0;
}
Output:
Time Complexity :- The update function and getSum function runs for O(log(n)) and we
are iterating over n elements. So overall time complexity is : O(nlogn).
Auxiliary space : O(n)
This article is contributed by Abhiraj Smit. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/count-inversions-array-set-3-using-bit/
573
Chapter 97
Count minimum bits to flip such that XOR of A and B equal to C - GeeksforGeeks
Given a sequence of three binary sequences A, B and C of N bits. Count the minimum bits
required to flip in A and B such that XOR of A and B is equal to C. For Example :
Input: N = 3
A = 110
B = 101
C = 001
Output: 1
We only need to flip the bit of 2nd position
of either A or B, such that A ^ B = C i.e.,
100 ^ 101 = 001
A Naive approach is to generate all possible combination of bits in A and B and then
XORing them to Check whether it is equal to C or not. Time complexity of this approach
grows exponentially so it would not be better for large value of N.
An Efficient approach is to use concept of XOR.
574
Chapter 97. Count minimum bits to flip such that XOR of A and B equal to C
1 0 - 1
1 1 - 0
If we generalize, we will find that at any position of A and B, we just only need to flip ith (0
to N-1) position of either A or B otherwise we will not able to achieve minimum no of Bits.
So at any position of i (0 to N-1) you will encounter two type of situation i.e., either A[i]
== B[i] or A[i] != B[i]. Let’s discuss it one by one.
• If A[i] == B[i] then XOR of these bits will be 0, two cases arise in C[]: C[i]==0 or
C[i]==1.
If C[i] == 0, then no need to flip the bit but if C[i] == 1 then we have to flip the bit
either in A[i] or B[i] so that 1^0 == 1 or 0^1 == 1.
• If A[i] != B[i] then XOR of these Bits gives a 1, In C two cases again arise i.e., either
C[i] == 0 or C[i] == 1.
Therefore if C[i] == 1, then we need not to flip the bit but if C[i] == 0, then we need
to flip the bit either in A[i] or B[i] so that 0^0==0 or 1^1==0
C++
575
Chapter 97. Count minimum bits to flip such that XOR of A and B equal to C
cout << totalFlips(a, b, c, N);
return 0;
}
Java
Python
576
Chapter 97. Count minimum bits to flip such that XOR of A and B equal to C
C#
577
Chapter 97. Count minimum bits to flip such that XOR of A and B equal to C
// Driver code
public static void Main()
{
// N represent total count of Bits
int N = 5;
string a = "10100";
string b = "00010";
string c = "10011";
Console.Write(totalFlips(a, b, c, N));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP code to count the
// Minimum bits in A and B
function totalFlips($A, $B, $C, $N)
{
$count = 0;
for ($i = 0; $i < $N; ++$i)
{
// If both A[i] and
// B[i] are equal
if ($A[$i] == $B[$i] &&
$C[$i] == '1')
++$count;
// If Both A and
// B are unequal
else if ($A[$i] != $B[$i] &&
$C[$i] == '0')
++$count;
}
return $count;
}
// Driver Code
// N represent total count of Bits
$N = 5;
$a = "10100";
$b = "00010";
578
Chapter 97. Count minimum bits to flip such that XOR of A and B equal to C
$c = "10011";
echo totalFlips($a, $b, $c, $N);
// This code is contributed by nitin mittal.
?>
Output:
Source
https://www.geeksforgeeks.org/count-minimum-bits-flip-xor-b-equal-c/
579
Chapter 98
Input : a = 10, b = 20
Output : 4
Binary representation of a is 00001010
Binary representation of b is 00010100
We need to flip highlighted four bits in a
to make it b.
Input : a = 7, b = 10
Output : 3
Binary representation of a is 00000111
Binary representation of b is 00001010
We need to flip highlighted three bits in a
to make it b.
XOR of two number will have set bits only at those places where A differs from B.
580
Chapter 98. Count number of bits to be flipped to convert A to B
C++
Java
581
Chapter 98. Count number of bits to be flipped to convert A to B
{
int count = 0;
while (n != 0) {
count += n & 1;
n >>= 1;
}
return count;
}
// Function that return count of
// flipped number
public static int FlippedCount(int a, int b)
{
// Return count of set bits in
// a XOR b
return countSetBits(a ^ b);
}
// Driver code
public static void main(String[] args)
{
int a = 10;
int b = 20;
System.out.print(FlippedCount(a, b));
}
}
// This code is contributed by rishabh_jain
Python3
582
Chapter 98. Count number of bits to be flipped to convert A to B
return countSetBits(a^b)
# Driver code
a = 10
b = 20
print(FlippedCount(a, b))
# This code is contributed by "Sharad_Bhardwaj".
C#
583
Chapter 98. Count number of bits to be flipped to convert A to B
PHP
<?php
// Count number of bits to be
// flipped to convert A into B
// Function that count set bits
function countSetBits($n)
{
$count = 0;
while($n)
{
$count += $n & 1;
$n >>= 1;
}
return $count;
}
// Function that return
// count of flipped number
function FlippedCount($a, $b)
{
// Return count of set
// bits in a XOR b
return countSetBits($a ^ $b);
}
// Driver code
$a = 10;
$b = 20;
echo FlippedCount($a, $b);
// This code is contributed by mits
?>
Output :
584
Chapter 98. Count number of bits to be flipped to convert A to B
Source
https://www.geeksforgeeks.org/count-number-of-bits-to-be-flipped-to-convert-a-to-b/
585
Chapter 99
Input : S = { 1, 2, 2, 3, 5 }, L = 1 and R = 5
Output : 5
Explanation : Every number between
1 and 5 can be made out using some subset of S.
{1 as 1, 2 as 2, 3 as 3, 4 as 2 + 2 and 5 as 5}
Input : S = { 2, 3, 5 }, L = 1 and R = 7
Output : 4
Explanation : Only 4 numbers between
1 and 7 can be made out, i.e. {2, 3, 5, 7}.
3 numbers which are {1, 4, 6} can't be made out in any way.
586
Chapter 99. Count number of distinct sum subsets within given range
and i for prefix[1..i] to answer each query in O(1) if there are more than query being asked
simultaneously. For a query L and R, answer would be simply prefix[R] – prefix[L – 1]
587
Chapter 99. Count number of distinct sum subsets within given range
int prefix[SZ];
// Intializing the prefix array to zero
memset(prefix, 0, sizeof(prefix));
// Build the prefix array
for (int i = 1; i < SZ; i++) {
prefix[i] = prefix[i - 1] + BS[i];
}
// Answer the given query
int ans = prefix[R] - prefix[L - 1];
return ans;
}
// Driver Code to test above functions
int main()
{
int S[] = { 1, 2, 3, 5, 7 };
int N = sizeof(S) / sizeof(S[0]);
int L = 1, R = 18;
cout << countOfpossibleNumbers(S, N, L, R);
return 0;
}
Output:
18
Time Complexity : O(S*Z) where S*Z is the maximum sum for given constraints, i.e.
105
Source
https://www.geeksforgeeks.org/count-number-distinct-sum-subsets-within-given-range/
588
Chapter 100
Brute Force approach O(2n ): One naive approach is to generate all the 2n subsets and
count all the subsets having XOR value K, but this approach will not be efficient for large
values of n.
Dynamic Programming Approach O(n*m):
We define a number m such that m = pow(2,(log2(max(arr))+1)) – 1. This number is
actually the maximum value any XOR subset will acquire. We get this number by counting
bits in largest number. We create a 2D array dp[n+1][m+1], such that dp[i][j] equals to
the number of subsets having XOR value j from subsets of arr[0…i-1].
We fill the dp array as following:
589
Chapter 100. Count number of subsets having a particular XOR value
3. Iterate over all the values of arr[i] from left to right and for each arr[i], iterate over
all the possible values of XOR i.e from 0 to m (both inclusive) and fill the dp array
asfollowing:
for i = 1 to n:
for j = 0 to m:
dp[i][j] = dp[i-1][j] + dp[i-1][j^arr[i-1]]
This can be explained as, if there is a subset arr[0…i-2] with XOR value j, then there
also exists a subset arr[0…i-1] with XOR value j. also if there exists a subset arr[0….i-2]
with XOR value j^arr[i] then clearly there exist a subset arr[0…i-1] with XOR value j,
as j ^ arr[i-1] ^ arr[i-1] = j.
4. Counting the number of subsets with XOR value k: Since dp[i][j] is the number of
subsets having j as XOR value from the subsets of arr[0..i-1], then the number of
subsets from set arr[0..n] having XOR value as K will be dp[n][K]
C/C++
590
Chapter 100. Count number of subsets having a particular XOR value
PHP
<?php
// PHP arr dynamic programming
// solution to finding the number
// of subsets having xor of their
// elements as k
// Returns count of subsets of
// arr[] with XOR value equals to k.
function subsetXOR($arr, $n, $k)
{
// Find maximum element in arr[]
$max_ele = $arr[0];
for ($i = 1; $i < $n; $i++)
if ($arr[$i] > $max_ele)
$max_ele = $arr[$i];
// Maximum possible XOR value
$m = (1 << (int)(log($max_ele,
2) + 1) ) - 1;
// The value of dp[i][j] is the
// number of subsets having
// XOR of their elements as j
// from the set arr[0...i-1]
// Initializing all the
// values of dp[i][j] as 0
for ($i = 0; $i <= $n; $i++)
591
Chapter 100. Count number of subsets having a particular XOR value
Output :
Count of subsets is 4
This article is contributed by Pranay Pandey. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t
Source
https://www.geeksforgeeks.org/count-number-of-subsets-having-a-particular-xor-value/
592
Chapter 101
1. 0 <= a <= x
2. a XOR x = a + x
Examples :
Input : 5
Output : 2
Explanation: For x = 5, following 2 values
of 'a' satisfy the conditions:
5 XOR 0 = 5+0
5 XOR 2 = 5+2
Input : 10
Output : 4
Explanation: For x = 10, following 4 values
of 'a' satisfy the conditions:
10 XOR 0 = 10+0
10 XOR 1 = 10+1
10 XOR 4 = 10+4
10 XOR 5 = 10+5
Naive Approach:
A Simple approach is to check for all values of ‘a’ between 0 and ‘x’ (both inclusive) and
calculate its XOR with x and check if the condition 2 satisfies.
C++
593
Chapter 101. Count numbers whose sum with x is equal to XOR with x
Java
594
Chapter 101. Count numbers whose sum with x is equal to XOR with x
return count;
}
public static void main (String[] args)
{
int x=10;
System.out.println(FindValues(x));
}
}
C#
PHP
<?php
595
Chapter 101. Count numbers whose sum with x is equal to XOR with x
Output :
596
Chapter 101. Count numbers whose sum with x is equal to XOR with x
Java
597
Chapter 101. Count numbers whose sum with x is equal to XOR with x
C#
// C# program to count
// numbers whose bitwise
// XOR and sum with x
// are equal
using System;
598
Chapter 101. Count numbers whose sum with x is equal to XOR with x
class GFG
{
// Function to find total
// 0 bit in a number
static int CountZeroBit(int x)
{
int count = 0;
while (x > 0)
{
if ((x & 1) == 0)
count++;
x >>= 1;
}
return count;
}
// Function to find Count
// of non-negative numbers
// less than or equal to x,
// whose bitwise XOR and
// SUM with x are equal.
static int CountXORandSumEqual(int x)
{
// count number of
// zero bit in x
int count = CountZeroBit(x);
// power of 2 to count
return (1 << count);
}
// Driver code
static public void Main ()
{
int x = 10;
Console.WriteLine(CountXORandSumEqual(x));
}
}
// The code is contributed by ajit
PHP
<?php
// PHP program to count numbers whose bitwise
// XOR and sum with x are equal
599
Chapter 101. Count numbers whose sum with x is equal to XOR with x
Output:
Source
https://www.geeksforgeeks.org/count-numbers-whose-sum-x-equal-xor-x/
600
Chapter 102
Count of divisors having more set bits than quotient on dividing N - GeeksforGeeks
Given a positive integer N. The task is to find the number of divisor (say d) which give
quotient (say q) on integer division (i.e q = N/d) such that quotient have less or equal set
bit than divisor. In other words, find number of possible value of ‘d’ which will produce ‘q’
on integer dividing ‘n’ (q = N/d) such that ‘q’ have less or equal set bits (atleast 1) than
‘d’.
Examples :
Input : N = 5
Output : 4
for d = 1 (set bit = 1),
q = 5/1 = 5 (set bit = 2), count = 0.
for d = 2 (set bit = 1),
q = 5/2 = 2 (set bit = 1), count = 1.
for d = 3 (set bit = 2),
q = 5/3 = 1 (set bit = 1), count = 2.
for d = 4 (set bit = 1),
q = 5/4 = 1 (set bit = 1), count = 3.
for d = 5 (set bit = 2),
q = 5/5 = 1 (set bit = 1), count = 4.
Input : N = 3
Output : 2
Observe, for all d > n, q have 0 set bit so there is no point to go above n.
601
Chapter 102. Count of divisors having more set bits than quotient on dividing N
Also, for n/2 < d <= n, it will return q = 1, which have 1 set bit which will always be
less
than or equal to d. And, minimum possible value of d is 1. So, possible value of d is from 1
to n.
Now, observe on dividing n by d, where 1 <= d <= n, it will give q in sorted order
(decreasing).
So, with increasing d we will get decreasing q. So, we get the two sorted sequence, one for
increasing d
and other for decreasing q. Now, observe initially the number of set bit of d is greater than
q but after
a point number of set bit of d is less than or equal to q.
So, our problem reduce to find that point i.e. ‘x’ for the value of d, from 1 <= d <= n,
such that q have less than or equal set bit to d.
So, count of possible d such that q have less than or equal set bit to d will be equal to n –
x + 1.
Below is the implementation of this approach :
C++
602
Chapter 102. Count of divisors having more set bits than quotient on dividing N
Java
603
Chapter 102. Count of divisors having more set bits than quotient on dividing N
{
// Return the count of set bit.
static int bit(int x)
{
int ans = 0;
while (x > 0)
{
x /= 2;
ans++;
}
return ans;
}
// check if q and d have
// same number of set bit.
static boolean check(int d, int x)
{
if (bit(x / d) <= bit(d))
return true;
return false;
}
// Binary Search to find
// the point at which
// number of set in q is
// less than or equal to d.
static int bs(int n)
{
int l = 1, r = (int)Math.sqrt(n);
// while left index is
// less than right index
while (l < r)
{
// finding the middle.
int m = (l + r) / 2;
// check if q and d have
// same number of
// set it or not.
if (check(m, n))
r = m;
else
l = m + 1;
}
604
Chapter 102. Count of divisors having more set bits than quotient on dividing N
if (!check(l, n))
return l + 1;
else
return l;
}
static int countDivisor(int n)
{
return n - bs(n) + 1;
}
// Driver Code
static public void main (String[] args)
{
int n = 5;
System.out.println(countDivisor(n));
}
}
// This code is contributed by anuj_67.
Python3
605
Chapter 102. Count of divisors having more set bits than quotient on dividing N
C#
606
Chapter 102. Count of divisors having more set bits than quotient on dividing N
while (x > 0) {
x /= 2;
ans++;
}
return ans;
}
// check if q and d have
// same number of set bit.
static bool check(int d, int x)
{
if (bit(x / d) <= bit(d))
return true;
return false;
}
// Binary Search to find
// the point at which
// number of set in q is
// less than or equal to d.
static int bs(int n)
{
int l = 1, r = (int)Math.Sqrt(n);
// while left index is
// less than right index
while (l < r) {
// finding the middle.
int m = (l + r) / 2;
// check if q and d have
// same number of
// set it or not.
if (check(m, n))
r = m;
else
l = m + 1;
}
if (!check(l, n))
return l + 1;
else
return l;
}
607
Chapter 102. Count of divisors having more set bits than quotient on dividing N
PHP
<?php
// PHP Program to find number of Divisors
// which on integer division produce quotient
// having less set bit than divisor
// Return the count of set bit.
function bit( $x)
{
$ans = 0;
while ($x)
{
$x /= 2;
$ans++;
}
return $ans;
}
// check if q and d have
// same number of set bit.
function check( $d, $x)
{
if (bit($x /$d) <= bit($d))
return true;
return false;
}
// Binary Search to find
// the point at which
608
Chapter 102. Count of divisors having more set bits than quotient on dividing N
Output:
609
Chapter 102. Count of divisors having more set bits than quotient on dividing N
Source
https://www.geeksforgeeks.org/count-divisors-set-bits-quotient-dividing-n/
610
Chapter 103
Count pairs in an array which have at least one digit common - GeeksforGeeks
Given an array of N numbers. Find out the number of pairs i and j such that i < j and Ai
and Aj have atleast one digit common (For e.g. (11, 19) have 1 digit common but (36, 48)
have no digit common)
Examples:
Method 1 (Brute Force) A naive approach to solve this problem is just by running two
nested loops and consider all possible pairs. We can check if the two numbers have atleast
one common digit, by extracting every digit of first number and try to find it in the extracted
digits of second number. The task would become much easier we simply convert them into
strings.
Below is the naive implementation.
C++
611
Chapter 103. Count pairs in an array which have at least one digit common
// otherwise false
bool checkValidPair(int num1, int num2)
{
// converting integers to strings
string s1 = to_string(num1);
string s2 = to_string(num2);
// Iterate over the strings and check
// if a character in first string is also
// present in second string, return true
for (int i = 0; i < s1.size(); i++)
for (int j = 0; j < s2.size(); j++)
if (s1[i] == s2[j])
return true;
// No common digit found
return false;
}
// Returns the number of valid pairs
int countPairs(int arr[], int n)
{
int numberOfPairs = 0;
// Iterate over all possible pairs
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (checkValidPair(arr[i], arr[j]))
numberOfPairs++;
return numberOfPairs;
}
// Driver Code to test above functions
int main()
{
int arr[] = { 10, 12, 24 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countPairs(arr, n) << endl;
return 0;
}
Java
612
Chapter 103. Count pairs in an array which have at least one digit common
class GFG
{
// Returns true if the pair
// is valid, otherwise false
static boolean checkValidPair(int num1,
int num2)
{
// converting integers
// to strings
String s1 = Integer.toString(num1);
String s2 = Integer.toString(num2);
// Iterate over the strings
// and check if a character
// in first string is also
// present in second string,
// return true
for (int i = 0; i < s1.length(); i++)
for (int j = 0; j < s2.length(); j++)
if (s1.charAt(i) == s2.charAt(j))
return true;
// No common
// digit found
return false;
}
// Returns the number
// of valid pairs
static int countPairs(int []arr, int n)
{
int numberOfPairs = 0;
// Iterate over all
// possible pairs
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (checkValidPair(arr[i], arr[j]))
numberOfPairs++;
return numberOfPairs;
}
// Driver Code
public static void main(String args[])
{
613
Chapter 103. Count pairs in an array which have at least one digit common
C#
614
Chapter 103. Count pairs in an array which have at least one digit common
return numberOfPairs;
}
// Driver Code to test above functions
static void Main()
{
int []arr = new int[]{ 10, 12, 24 };
int n = arr.Length;
Console.WriteLine(countPairs(arr, n));
}
}
// This code is contributed by manish shaw.
Output
Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask - 1 1 1 1 1 1 1 1 1 1
Now we just have to extract every digit of a number and make the corresponding bit set
(1 << ith digit) and store the whole number as mask. Careful analysis suggests that the
maximum value of mask is 1023 in decimal (which contains all the digits from 0 – 9). Since
the same set of digits can exists in more than one number, we need to maintain a frequency
array to store the count of mask value.
Let the frequencies of two masks i and j be freqi and freqj respectively,
If(i AND j) return true, means ith and jth mask contains atleast one common set
bit which in turn implies that the numbers from which these masks have been
built also contain a common digit
then,
615
Chapter 103. Count pairs in an array which have at least one digit common
C++
616
Chapter 103. Count pairs in an array which have at least one digit common
Time Complexity: O(N + 1024 * 1024), where N is the size of the array.
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/count-pairs-array-least-one-digit-common/
617
Chapter 104
Input: N = 4
A[] = { 5, 1, 3, 2 }
Output: 3
Since pair of A[] = ( 5, 1 ), ( 5, 3 ), ( 5, 2 ), ( 1, 3 ), ( 1, 2 ), ( 3, 2 )
5 AND 1 = 1, 5 AND 3 = 1, 5 AND 2 = 0,
1 AND 3 = 1, 1 AND 2 = 0,
3 AND 2 = 2
Total odd pair A( i, j ) = 3
Input : N = 6
A[] = { 5, 9, 0, 6, 7, 3 }
Output :6
Since pair of A[] =
( 5, 9 ) = 1, ( 5, 0 ) = 0, ( 5, 6 ) = 4, ( 5, 7 ) = 5, ( 5, 3 ) = 1,
( 9, 0 ) = 0, ( 9, 6 ) = 0, ( 9, 7 ) = 1, ( 9, 3 ) = 1,
( 0, 6 ) = 0, ( 0, 7 ) = 0, ( 0, 3 ) = 0,
( 6, 7 ) = 6, ( 6, 3 ) = 2,
( 7, 3 ) = 3
A naive approach is to check for every pair and print the count of pairs.
Below is the implementation of the above approach:
C++
618
Chapter 104. Count pairs with Bitwise AND as ODD number
Java
619
Chapter 104. Count pairs with Bitwise AND as ODD number
C#
620
Chapter 104. Count pairs with Bitwise AND as ODD number
class GFG
{
// Function to count
// number of odd pairs
static int findOddPair(int []A,
int N)
{
int i, j;
// variable for counting
// odd pairs
int oddPair = 0;
// find all pairs
for (i = 0; i < N; i++)
{
for (j = i + 1; j < N; j++)
{
// find AND operation
// check odd or even
if ((A[i] & A[j]) % 2 != 0)
oddPair++;
}
}
// return number
// of odd pair
return oddPair;
}
// Driver Code
public static void Main()
{
int []a = { 5, 1, 3, 2 };
int n = a.Length;
// calling function findOddPair
// and print number of odd pair
Console.WriteLine(findOddPair(a, n));
}
}
// This code is contributed
// inder_verma.
Python
621
Chapter 104. Count pairs with Bitwise AND as ODD number
PHP
<?php
// PHP program to count pairs
// with AND giving a odd number
// Function to count
// number of odd pairs
function findOddPair(&$A, $N)
{
// variable for counting
// odd pairs
$oddPair = 0;
622
Chapter 104. Count pairs with Bitwise AND as ODD number
Output:
Time Complexity:O(N^2)
An efficient solution is to count the odd numbers. Then return count * (count –
1)/2 because AND of two numbers can be odd only if only if a pair of both numbers are odd.
C++
623
Chapter 104. Count pairs with Bitwise AND as ODD number
Java
624
Chapter 104. Count pairs with Bitwise AND as ODD number
Python
PHP
<?php
// PHP program to count
// pairs with Odd AND
function findOddPair(&$A, $N)
{
// Count total odd numbers
$count = 0;
for ($i = 0; $i < $N; $i++)
if (($A[$i] % 2 == 1))
$count++;
625
Chapter 104. Count pairs with Bitwise AND as ODD number
// return count of even pair
return $count * ($count - 1) / 2;
}
// Driver Code
$a = array(5, 1, 3, 2 );
$n = sizeof($a);
// calling function findOddPair
// and print number of odd pair
echo(findOddPair($a, $n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
Source
https://www.geeksforgeeks.org/count-pairs-with-bitwise-and-as-odd-number/
626
Chapter 105
Input : N = 4
A[] = { 5, 6, 2, 8 }
Output :3
Explanation :
Since pair of A[] = ( 5, 6 ), ( 5, 2 ), ( 5, 8 ),
( 6, 2 ), ( 6, 8 ), ( 2, 8 )
5 OR 6 = 7, 5 OR 2 = 7, 5 OR 8 = 13
6 OR 2 = 6, 6 OR 8 = 14, 2 OR 8 = 10
Total pair A( i, j ) = 6 and Even = 3
Input : N = 7
A[] = {8, 6, 2, 7, 3, 4, 9}
Output :6
C++
627
Chapter 105. Count pairs with Bitwise OR as Even number
int findEvenPair(int A[], int N)
{
int evenPair = 0;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
// find OR operation
// check odd or even
if ((A[i] | A[j]) % 2 == 0)
evenPair++;
}
}
// return count of even pair
return evenPair;
}
// Driver main
int main()
{
int A[] = { 5, 6, 2, 8 };
int N = sizeof(A) / sizeof(A[0]);
cout << findEvenPair(A, N) << endl;
return 0;
}
Java
628
Chapter 105. Count pairs with Bitwise OR as Even number
}
// return count of even pair
return evenPair;
}
// Driver Code
public static void main (String[] args)
{
int A[] = { 5, 6, 2, 8 };
int N = A.length;
System.out.println(findEvenPair(A, N));
}
}
// This code is contributed
// by inder_verma.
Python 3
629
Chapter 105. Count pairs with Bitwise OR as Even number
C#
// C# program to count
// pairs with even OR
using System;
class GFG
{
static int findEvenPair(int []A,
int N)
{
int evenPair = 0;
for (int i = 0; i < N; i++)
{
for (int j = i + 1; j < N; j++)
{
// find OR operation
// check odd or even
if ((A[i] | A[j]) % 2 == 0)
evenPair++;
}
}
// return count of even pair
return evenPair;
}
// Driver Code
public static void Main ()
{
int []A = { 5, 6, 2, 8 };
int N = A.Length;
Console.WriteLine(findEvenPair(A, N));
}
}
// This code is contributed
// by inder_verma.
PHP
<?php
// PHP program to count
// pairs with even OR
function findEvenPair($A, $N)
630
Chapter 105. Count pairs with Bitwise OR as Even number
{
$evenPair = 0;
for ($i = 0; $i < $N; $i++)
{
for ($j = $i + 1; $j < $N; $j++)
{
// find OR operation
// check odd or even
if (($A[$i] | $A[$j]) % 2 == 0)
$evenPair++;
}
}
// return count of even pair
return $evenPair;
}
// Driver Code
$A = array(5, 6, 2, 8);
$N = count($A);
echo findEvenPair($A, $N);
// This code is contributed
// by inder_verma.
?>
Output:
631
Chapter 105. Count pairs with Bitwise OR as Even number
Java
632
Chapter 105. Count pairs with Bitwise OR as Even number
C#
// C# program to count
// pairs with even OR
using System;
class GFG
{
static int findEvenPair(int []A, int N)
{
// Count total even numbers
// in array.
int count = 0;
for (int i = 0; i < N; i++)
if ((!((A[i] & 1) > 0)))
count++;
// return count of even pair
return count * (count - 1) / 2;
}
// Driver Code
public static void Main (String[] args)
{
int []A = { 5, 6, 2, 8 };
int N = A.Length;
Console.WriteLine(findEvenPair(A, N));
}
}
// This code is contributed
// by Kirti_Mangal
Output:
Source
https://www.geeksforgeeks.org/count-pairs-with-bitwise-or-as-even-number/
633
Chapter 106
Input : N = 5
A[] = { 5, 4, 7, 2, 1}
Output :6
Since pair of A[] =
( 5, 4 ) = 1( 5, 7 ) = 2( 5, 2 ) = 7( 5, 1 ) = 4
( 4, 7 ) = 3( 4, 2 ) = 6( 4, 1 ) = 5
( 7, 2 ) = 5( 7, 1 ) = 6
( 2, 1 ) = 3
Total XOR ODD pair = 6
Input : N = 7
A[] = { 7, 2, 8, 1, 0, 5, 11 }
Output :12
Since pair of A[] =
( 7, 2 ) = 5( 7, 8 ) = 15( 7, 1 ) = 6( 7, 0 ) = 7( 7, 5 ) = 2( 7, 11 ) = 12
( 2, 8 ) = 10( 2, 1 ) = 3( 2, 0 ) = 2( 2, 5 ) = 7( 2, 11 ) = 9
( 8, 1 ) = 9( 8, 0 ) = 8( 8, 5 ) = 13( 8, 11 ) = 3
( 1, 0 ) = 1( 1, 5 ) = 4( 1, 11 ) = 10
( 0, 5 ) = 5( 0, 11 ) = 11
( 5, 11 ) = 14
A naive approach is to check for every pair and print the count of pairs.
634
Chapter 106. Count pairs with Bitwise XOR as ODD number
C++
Java
635
Chapter 106. Count pairs with Bitwise XOR as ODD number
636
Chapter 106. Count pairs with Bitwise XOR as ODD number
Python3
C#
637
Chapter 106. Count pairs with Bitwise XOR as ODD number
638
Chapter 106. Count pairs with Bitwise XOR as ODD number
[/sourcecode]
OUTPUT:
C++
Java
639
Chapter 106. Count pairs with Bitwise XOR as ODD number
Python3
640
Chapter 106. Count pairs with Bitwise XOR as ODD number
for i in range(0 , N) :
if (A[i] % 2 == 0) :
count+=1
# return number of odd pair
return count * (N - count)
# Driver Code
if __name__=='__main__':
a = [5, 4, 7, 2, 1]
n = len(a)
print(findOddPair(a,n))
# this code is contributed by Smitha Dinesh Semwal
C#
641
Chapter 106. Count pairs with Bitwise XOR as ODD number
Output:
Source
https://www.geeksforgeeks.org/count-pairs-with-bitwise-xor-as-odd-number/
642
Chapter 107
Input : arr[] = { 1, 2, 3 }
Output : 2
All pairs of array
1 ^ 2 = 3
1 ^ 3 = 2
2 ^ 3 = 1
Input : arr[] = { 1, 2, 3, 4 }
Output : 4
Naive Approach: We can find pairs whose XOR is odd by running two loops. If XOR of
two number is odd increase count of pairs.
C++
643
Chapter 107. Count pairs with Odd XOR
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
// If XOR is odd increase count
if ((arr[i] ^ arr[j]) % 2 == 1)
count++;
}
// Return count
return count;
}
// Driver program to test countXorPair()
int main()
{
int arr[] = { 1, 2, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countXorPair(arr, n);
return 0;
}
Java
644
Chapter 107. Count pairs with Odd XOR
Python 3
C#
645
Chapter 107. Count pairs with Odd XOR
PHP
<?php
// PHP program to count
// pairs in array
// whose XOR is odd
// A function will
// return number of pair
// whose XOR is odd
function countXorPair($arr,$n)
{
// To store count
// of XOR pair
$count = 0;
for ($i = 0; $i < $n; $i++)
{
646
Chapter 107. Count pairs with Odd XOR
Output:
Therefore total pairs in array whose XOR is odd will be equal to count of odd numbers
multiplied by count of even numbers.
C++
647
Chapter 107. Count pairs with Odd XOR
Java
648
Chapter 107. Count pairs with Odd XOR
else
odd++;
}
// Return number of pairs
return odd * even;
}
// Driver program to test countXorPair()
public static void main(String[] args)
{
int arr[] = { 1, 2, 3 };
System.out.println(countXorPair(arr, arr.length));
}
}
Python 3
649
Chapter 107. Count pairs with Odd XOR
# This code is contributed
# by ChitraNayal
C#
PHP
<?php
// PHP program to count pairs in array
650
Chapter 107. Count pairs with Odd XOR
Output :
Source
https://www.geeksforgeeks.org/count-pairs-odd-xor/
651
Chapter 108
Input : n = 42, l = 2, r = 5
Output : 2
(42)10 = (101010)2
There are '2' set bits in the range 2 to 5.
Input : n = 79, l = 1, r = 4
Output : 4
1. Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number
num having r number of bits and bits in the range l to r are the only set bits.
2. Count number of set bits in the number (n & num). Refer this post.
C++
652
Chapter 108. Count set bits in a range
Java
653
Chapter 108. Count set bits in a range
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}
// function to count set bits in the given range
static int countSetBitsInGivenRange(int n, int l, int r)
{
// calculating a number 'num' having 'r' number
// of bits and bits in the range l to r are the
// only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// returns number of set bits in the range
// 'l' to 'r' in 'n'
return countSetBits(n & num);
}
// Driver code
public static void main(String[] args)
{
int n = 42;
int l = 2, r = 5;
System.out.print(countSetBitsInGivenRange(n, l, r));
}
}
// This code is contributed by Anant Agarwal.
Python3
654
Chapter 108. Count set bits in a range
# function to count set bits in
# the given range
def countSetBitsInGivenRange(n, l, r):
# calculating a number 'num' having
# 'r' number of bits and bits in the
# range l to r are the only set bits
num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
# returns number of set bits in the range
# 'l' to 'r' in 'n'
return countSetBits(n & num)
# Driver program to test above
n = 42
l = 2
r = 5
ans = countSetBitsInGivenRange(n, l, r)
print (ans)
# This code is contributed by Saloni Gupta.
C#
655
Chapter 108. Count set bits in a range
{
// calculating a number 'num' having 'r' number
// of bits and bits in the range l to r are the
// only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// returns number of set bits in the range
// 'l' to 'r' in 'n'
return countSetBits(n & num);
}
//Driver code
public static void Main()
{
int n = 42;
int l = 2, r = 5;
Console.WriteLine(countSetBitsInGivenRange(n, l, r));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP implementation to count
// set bits in the given range
// Function to get no of set bits in
// the binary representation of 'n'
function countSetBits($n)
{
$count = 0;
while ($n)
{
$n &= ($n - 1);
$count++;
}
return $count;
}
// function to count set
// bits in the given range
function countSetBitsInGivenRange($n, $l, $r)
{
656
Chapter 108. Count set bits in a range
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/count-set-bits-range/
657
Chapter 109
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits
Input : n = 13
Output : 3
Binary representation of 11 is 1101 and has 3 set bits
658
Chapter 109. Count set bits in an integer
1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is
then increment the set bit count. See below program.
#include <stdio.h>
/* Function to get no of set bits in binary
representation of positive integer n */
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while (n)
{
count += n & 1;
n >>= 1;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i = 9;
printf("%d", countSetBits(i));
return 0;
659
Chapter 109. Count set bits in an integer
Java
Python3
660
Chapter 109. Count set bits in an integer
i = 9
print(countSetBits(i))
# This code is contributed by
# Smitha Dinesh Semwal
C#
PHP
<?php
// Function to get no of set
// bits in binary representation
// of positive integer n
function countSetBits($n)
{
$count = 0;
661
Chapter 109. Count set bits in an integer
while ($n)
{
$count += $n & 1;
$n >>= 1;
}
return $count;
}
// Driver Code
$i = 9;
echo countSetBits($i);
// This code is contributed by ajit
?>
Output :
C++
662
Chapter 109. Count set bits in an integer
int main()
{
// get value from user
int n = 9;
// function calling
cout << countSetBits(n);
return 0;
}
// This code is contributed by Raj.
Java
663
Chapter 109. Count set bits in an integer
Python3
C#
// C# implementation of recursive
// approach to find the number of
// set bits in binary representation
// of positive integer n
using System;
class GFG
{
// recursive function
// to count set bits
public static int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
664
Chapter 109. Count set bits in an integer
else
// if last bit set
// add 1 else add 0
return (n & 1) +
countSetBits(n >> 1);
}
// Driver code
static public void Main ()
{
// get value
// from user
int n = 9;
// function calling
Console.WriteLine(countSetBits(n));
}
}
// This code is contributed by aj_36
PHP
<?php
// PHP implementation of recursive
// approach to find the number of
// set bits in binary representation
// of positive integer n
// recursive function
// to count set bits
function countSetBits($n)
{
// base case
if ($n == 0)
return 0;
else
// if last bit set
// add 1 else add 0
return ($n & 1) +
countSetBits($n >> 1);
}
// Driver code
665
Chapter 109. Count set bits in an integer
// get value from user
$n = 9;
// function calling
echo countSetBits($n);
// This code is contributed by m_kit.
?>
Output :
1 Initialize count: = 0
2 If integer n is not zero
(a) Do bitwise & with (n-1) and assign the value back to n
n: = n&(n-1)
(b) Increment count by 1
(c) go to step 2
3 Else return count
#include<stdio.h>
/* Function to get no of set bits in binary
representation of passed binary no. */
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n)
{
666
Chapter 109. Count set bits in an integer
Java
Python3
667
Chapter 109. Count set bits in an integer
C#
668
Chapter 109. Count set bits in an integer
}
// This code is contributed by ajit
PHP
<?php
/* Function to get no of
set bits in binary
representation of passed
binary no. */
function countSetBits($n)
{
$count = 0;
while ($n)
{
$n &= ($n - 1) ;
$count++;
}
return $count;
}
// Driver Code
$i = 9;
echo countSetBits($i);
// This code is contributed
// by akt_mit
?>
Output :
n = 9 (1001)
count = 0
669
Chapter 109. Count set bits in an integer
C++
Java
670
Chapter 109. Count set bits in an integer
Python3
671
Chapter 109. Count set bits in an integer
n = 9
# function calling
print(countSetBits(n))
# This code is contributed by sunnysingh
C#
PHP
<?php
672
Chapter 109. Count set bits in an integer
Output :
3. Using Lookup table: We can count bits in O(1) time using lookup table. Please
seehttp://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable for details.
We can find one use of counting set bits at Count number of bits to be flipped to convert A
to B
Note: In GCC, we can directly count set bits using __builtin_popcount(). So we can
avoid a separate function for counting set bits.
C++
673
Chapter 109. Count set bits in an integer
PHP
<?php
// PHP program to demonstrate
// __builtin_popcount()
// Driver code
$t = log10(4);
$x = log(15,2);
$tt = ceil($t);
$xx = ceil($x);
echo ($tt), "\n";
echo ($xx), "\n";
// This code is contributed
// by jit_t
?>
Output :
1
4
Source
https://www.geeksforgeeks.org/count-set-bits-in-an-integer/
674
Chapter 110
Input : n = 6
Output : 2
Binary representation of 6 is 110
and has 2 set bits
Input : n = 13
Output : 3
Binary representation of 11 is 1101
and has 3 set bits
In the previous post we had seen different method that solved this problem in O(log n) time.
In this post we solve in O(1) using lookup table. Here we assume that the size of INT is
32-bits. It’s hard to count all 32 bits in one go using lookup table (” because it’s infeasible
to create lookup table of size 232 -1 “). So we break 32 bits into 8 bits of chunks( ow
lookup table of size (28 -1 ) index : 0-255 ).
LookUp Table
In lookup tale, we store count of set_bit of every
number that are in a range (0-255)
LookupTable[0] = 0 | binary 00000000 CountSetBits 0
LookupTable[1] = 1 | binary 00000001 CountSetBits 1
LookupTable[2] = 1 | binary 00000010 CountSetBits 1
LookupTanle[3] = 2 | binary 00000011 CountSetBits 2
675
Chapter 110. Count set bits in an integer using Lookup Table
676
Chapter 110. Count set bits in an integer using Lookup Table
}
int main()
{
// generate lookup table
for (int i = 0; i < 256; i++)
lookuptable[i] = (i & 1) + lookuptable[i / 2];
unsigned int N = 354;
cout << countSetBits(N) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-set-bits-integer-using-lookup-table/
677
Chapter 111
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits
Input : n = 11
Output : 3
Binary representation of 11 is 1101 and has 3 set bits
We have existing solution for this problem please refer Count set bits in an integer link. We
will solve this problem in Python using List comprehension. Approach is simple,
1. Convert given number into it’s binary representation using bin(number) function.
2. Now separate out all 1’s from binary representation of given number and print length
of list of 1’s.
678
Chapter 111. Count set bits using Python List comprehension
binary = bin(num)
# now separate out all 1's from binary string
# we need to skip starting two characters
# of binary string i.e; 0b
setBits = [ones for ones in binary[2:] if ones=='1']
print len(setBits)
# Driver program
if __name__ == "__main__":
num = 11
countSetBits(num)
Output:
Source
https://www.geeksforgeeks.org/count-set-bits-using-python-list-comprehension/
679
Chapter 112
Count smaller numbers whose XOR with n produces greater value - GeeksforGeeks
Given a positive integer n, count numbers x such that 0 < x <n and x^n > n where ^ is
bitwise XOR operation.
Examples:
Input : n = 12
Output : 3
Numbers are 1, 2 and 3
1^12 > 12, 2^12 > 12 and 3^12 > 12
Input : n = 11
Output : 4
Numbers are 4, 5, 6 and 7
A number may x produce a greater XOR value if x has a set bit at a position where n has
a 0 bit. So we traverse bits of n, and one by one consider all 0 bits. For every set bit at
position k (Considering k = 0 for rightmost bit, k = 1 for second rightmost bit, ..), we add
2 2k to result. For a bit at k-th position, there are 2k numbers with set bit 1.
Below is the implementation of the above idea.
C++
680
Chapter 112. Count smaller numbers whose XOR with n produces greater value
Java
681
Chapter 112. Count smaller numbers whose XOR with n produces greater value
682
Chapter 112. Count smaller numbers whose XOR with n produces greater value
System.out.println(countNumbers(n));
}
}
// This code is contributed by Smitha.
Python3
683
Chapter 112. Count smaller numbers whose XOR with n produces greater value
C#
684
Chapter 112. Count smaller numbers whose XOR with n produces greater value
// Driver code
public static void Main()
{
int n = 11;
Console.WriteLine(countNumbers(n));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to count
// numbers whose XOR with n
// produces a value more than n.
function countNumbers($n)
{
/* If there is a number
like m = 11110000,
then it is bigger
then 1110xxxx. x
can either 0 or 1.
So we have pow(2, k)
greater numbers where
k is position of
rightmost 1 in m.
Now by using XOR bit
at each position can
be changed. To change
bit at any position,
it needs to XOR it
with 1. */
// Position of current bit in n
$k = 0;
/* Traverse bits from LSB
(least significant bit)
to MSB */
// Initialize result
$count = 0;
while ($n > 0)
{
685
Chapter 112. Count smaller numbers whose XOR with n produces greater value
// If current bit is 0,
// then there are 2^k
// numbers with current
// bit 1 and whose XOR
// with n produces greater
// value
if (($n & 1) == 0)
$count += pow(2, $k);
// Increase position
// for next bit
$k += 1;
// Reduce n to
// find next bit
$n >>= 1;
}
return $count;
}
// Driver code
$n = 11;
echo countNumbers($n);
// This code is contributed by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/count-smaller-numbers-whose-xor-n-produces-greater-value/
686
Chapter 113
1. a XOR x > x
2. 0 < a < x
Examples :
Input : x = 10
Output : 5
Explanation: For x = 10, following 5 values
of 'a' satisfy the conditions:
1 XOR 10 = 11
4 XOR 10 = 14
5 XOR 10 = 15
6 XOR 10 = 12
7 XOR 10 = 13
Input : x = 2
Output : 1
Explanation: For x=2, we have just one value
1 XOR 2 = 3.
Naive Approach
A Simple approach is to check for all values of ‘a’ between 0 and ‘x’ and calculate its XOR
with x
687
Chapter 113. Count smaller values whose XOR with x is greater than x
C++
Java
688
Chapter 113. Count smaller values whose XOR with x is greater than x
System.out.println(countValues(x));
}
}
// This code is contributed by Saket Kumar
Python 3
C#
// C# program to find count of values
// whose XOR with x is greater than x
// and values are smaller than x
using System;
class GFG
{
static int countValues(int x)
{
int count = 0;
for (int i = 1; i < x; i++)
if ((i ^ x) > x)
count++;
return count;
}
689
Chapter 113. Count smaller values whose XOR with x is greater than x
public static void Main ()
{
int x = 10;
Console.Write(countValues(x));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find count of values
// whose XOR with x is greater than x
// and values are smaller than x
function countValues($x)
{
$count = 0;
for ($i = 1; $i < $x; $i++)
if (($i ^ $x) > $x)
$count++;
return $count;
}
// Driver code
$x = 10;
echo countValues($x);
// This code is contributed by anuj_67.
?>
Output :
690
Chapter 113. Count smaller values whose XOR with x is greater than x
Java
691
Chapter 113. Count smaller values whose XOR with x is greater than x
Python3
692
Chapter 113. Count smaller values whose XOR with x is greater than x
C#
// C# program to find count of values
// whose XOR with x is greater than x
// and values are smaller than x
using System;
class GFG
{
static int countValues(int x)
{
// Initialize result
int count = 0, n = 1;
// Traversing through all bits of x
while (x != 0)
{
// If current last bit of x is set
// then increment count by n. Here
693
Chapter 113. Count smaller values whose XOR with x is greater than x
PHP
<?php
// PHP program to find count
// of values whose XOR with
// x is greater than x and
// values are smaller than x
function countValues($x)
{
// Initialize result
$count = 0;
$n = 1;
// Traversing through
// all bits of x
while ($x != 0)
{
// If current last bit
// of x is set then
// increment count by
// n. Here n is a power
694
Chapter 113. Count smaller values whose XOR with x is greater than x
// of 2 corresponding
// to position of bit
if ($x % 2 == 0)
$count += $n;
// Simultaneously
// calculate the 2^n
$n *= 2;
// Replace x with x/2;
$x /= 2;
$x = (int)$x;
}
return $count;
}
// Driver code
$x = 10;
echo countValues($x);
// This code is contributed
// by Smitha
?>
Output :
Source
https://www.geeksforgeeks.org/count-smaller-values-whose-xor-x-greater-x/
695
Chapter 114
Input : n = 2
Output : 1
There are 4 strings of length 2, the
strings are 00, 01, 10 and 11. Only the
string 11 has consecutive 1's.
Input : n = 3
Output : 3
There are 8 strings of length 3, the
strings are 000, 001, 010, 011, 100,
101, 110 and 111. The strings with
consecutive 1's are 011, 110 and 111.
Input : n = 5
Output : 19
The reverse problem of counting strings without consecutive 1’s can be solved using Dynamic
Programming (See the solution here). We can use that solution and find the required count
using below steps.
1) Compute number of binary strings without consecutive 1’s using the approach discussed
here. Let this count be c.
2) Count of all possible binary strings with consecutive 1’s is 2^n where n is input length.
696
Chapter 114. Count strings with consecutive 1’s
C++
Java
697
Chapter 114. Count strings with consecutive 1’s
{
// Count binary strings without consecutive 1's.
// See the approach discussed on be
// ( http://goo.gl/p8A3sW )
int a[] = new int[n], b[] = new int[n];
a[0] = b[0] = 1;
for (int i = 1; i < n; i++) {
a[i] = a[i - 1] + b[i - 1];
b[i] = a[i - 1];
}
// Subtract a[n-1]+b[n-1]
from 2^n
return (1 << n) - a[n - 1] - b[n - 1];
}
// Driver program to test above functions
public static void main(String args[])
{
System.out.println(countStrings(5));
}
}
//This code is contributed by Nikita tiwari.
Python 3
698
Chapter 114. Count strings with consecutive 1’s
# Subtract a[n-1]+b[n-1] from 2^n
return (1 << n) - a[n - 1] - b[n - 1]
# Driver program
print(countStrings(5))
# This code is contributed
# by Nikita tiwari.
C#
699
Chapter 114. Count strings with consecutive 1’s
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to count all
// distinct binary strings
// with two consecutive 1's
// Returns count of n length binary
// strings with consecutive 1's
function countStrings($n)
{
// Count binary strings without consecutive 1's.
// See the approach discussed on be
// ( http://goo.gl/p8A3sW )
$a[$n] = 0;
$b[$n] = 0;
$a[0] = $b[0] = 1;
for ($i = 1; $i < $n; $i++)
{
$a[$i] = $a[$i - 1] + $b[$i - 1];
$b[$i] = $a[$i - 1];
}
// Subtract a[n-1]+b[n-1] from 2^n
return (1 << $n) - $a[$n - 1] -
$b[$n - 1];
}
// Driver Code
echo countStrings(5), "\n";
// This Code is contributed by Ajit
?>
Output :
19
Optimization:
Time complexity of above solution is O(n). We can optimize above solution to work in
O(Logn).
700
Chapter 114. Count strings with consecutive 1’s
If we take a closer look at the pattern of counting strings without consecutive 1’s, we can
observe that the count is actually (n+2)’th Fibonacci number for n >= 1. The Fibonacci
Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, ….
n = 1, count = 0 = 21 - fib(3)
n = 2, count = 1 = 22 - fib(4)
n = 3, count = 3 = 23 - fib(5)
n = 4, count = 8 = 24 - fib(6)
n = 5, count = 19 = 24 - fib(7)
................
We can find n’th Fibonacci Number in O(Log n) time (See method 4 here).
Improved By : jit_t
Source
https://www.geeksforgeeks.org/count-strings-with-consecutive-1s/
701
Chapter 115
Input : 13
Output : 4
Binary representation of 13 is 1001
Input : 183
Output : 8
Input : 4096
Output : 13
702
Chapter 115. Count total bits in a number
}
// Driven program
int main()
{
unsigned int num = 65;
printf("%d\n", countBits(num));
return 0;
}
Java
Python3
703
Chapter 115. Count total bits in a number
C#
PHP
<?php
// PHP program to find total
// bit in given number
function countBits($number)
{
704
Chapter 115. Count total bits in a number
// log function in base 2
// take only integer part
return (int)(log($number) /
log(2)) + 1;
}
// Driver Code
$num = 65;
echo(countBits($num));
// This code is contributed by Ajit.
?>
Output:
Java
705
Chapter 115. Count total bits in a number
Python3
706
Chapter 115. Count total bits in a number
C#
PHP
<?php
// PHP Code to get no of bits in binary
// representation of positive integer
// Function to get no of bits in binary
// representation of positive integer
function countBits($n)
{
$count = 0;
while ($n)
{
$count++;
$n >>= 1;
707
Chapter 115. Count total bits in a number
}
return $count;
}
// Driver Code
$i = 65;
echo(countBits($i));
// This code is contributed by Ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/count-total-bits-number/
708
Chapter 116
Input: n = 3
Output: 4
Input: n = 6
Output: 9
Input: n = 7
Output: 12
Input: n = 8
Output: 13
C++
709
Chapter 116. Count total set bits in all numbers from 1 to n
#include <stdio.h>
// A utility function to count set bits
// in a number x
unsigned int countSetBitsUtil(unsigned int x);
// Returns count of set bits present in all
// numbers from 1 to n
unsigned int countSetBits(unsigned int n)
{
int bitCount = 0; // initialize the result
for (int i = 1; i <= n; i++)
bitCount += countSetBitsUtil(i);
return bitCount;
}
// A utility function to count set bits
// in a number x
unsigned int countSetBitsUtil(unsigned int x)
{
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2);
}
// Driver program to test above functions
int main()
{
int n = 4;
printf("Total set bit count is %d", countSetBits(n));
return 0;
}
Java
710
Chapter 116. Count total set bits in all numbers from 1 to n
for (int i = 1; i <= n; i++)
bitCount += countSetBitsUtil(i);
return bitCount;
}
// A utility function to count set bits
// in a number x
static int countSetBitsUtil( int x)
{
if (x <= 0)
return 0;
return (x % 2 == 0 ? 0 : 1) +
countSetBitsUtil(x / 2);
}
// Driver program
public static void main(String[] args)
{
int n = 4;
System.out.print("Total set bit count is ");
System.out.print(countSetBits(n));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
711
Chapter 116. Count total set bits in all numbers from 1 to n
# in a number x
def countSetBitsUtil(x):
if (x <= 0):
return 0
return (0 if int(x % 2) == 0 else 1) + countSetBitsUtil(int(x / 2))
# Driver program
n = 8
print("Total set bit count is", countSetBits(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
712
Chapter 116. Count total set bits in all numbers from 1 to n
Output:
#include <bits/stdc++.h>
using namespace std;
// Function which counts set bits from 0 to n
int countSetBits(int n)
{
int i = 0;
// ans store sum of set bits from 0 to n
int ans = 0;
// while n greater than equal to 2^i
while ((1 << i) <= n) {
713
Chapter 116. Count total set bits in all numbers from 1 to n
Java
714
Chapter 116. Count total set bits in all numbers from 1 to n
// while n greater than equal to 2^i
while ((1 << i) <= n) {
// This k will get flipped after
// 2^i iterations
boolean k = false;
// change is iterator from 2^i to 1
int change = 1 << i;
// This will loop from 0 to n for
// every bit position
for (int j = 0; j <= n; j++) {
if (k == true)
ans += 1;
else
ans += 0;
if (change == 1) {
// When change = 1 flip the bit
k = !k;
// again set change to 2^i
change = 1 << i;
}
else {
change--;
}
}
// increment the position
i++;
}
return ans;
}
// Driver program
public static void main(String[] args)
{
int n = 17;
System.out.println(countSetBits(n));
}
}
715
Chapter 116. Count total set bits in all numbers from 1 to n
// This code is contributed by Sam007.
C#
using System;
class GFG
{
static int countSetBits(int n)
{
int i = 0;
// ans store sum of set bits from 0 to n
int ans = 0;
// while n greater than equal to 2^i
while ((1 << i) <= n) {
// This k will get flipped after
// 2^i iterations
bool k = false;
// change is iterator from 2^i to 1
int change = 1 << i;
// This will loop from 0 to n for
// every bit position
for (int j = 0; j <= n; j++) {
if (k == true)
ans += 1;
else
ans += 0;
if (change == 1) {
// When change = 1 flip the bit
k = !k;
// again set change to 2^i
change = 1 << i;
}
else {
change--;
}
}
716
Chapter 116. Count total set bits in all numbers from 1 to n
PHP
<?php
// Function which counts
// set bits from 0 to n
function countSetBits($n)
{
$i = 0;
// ans store sum of set
// bits from 0 to n
$ans = 0;
// while n greater than
// equal to 2^i
while ((1 << $i) <= $n)
{
// This k will get flipped
// after 2^i iterations
$k = 0;
// change is iterator
// from 2^i to 1
$change = 1 << $i;
// This will loop from 0 to n
// for every bit position
for ($j = 0; $j <= $n; $j++)
{
$ans += $k;
717
Chapter 116. Count total set bits in all numbers from 1 to n
if ($change == 1)
{
// When change = 1 flip
// the bit
$k = !$k;
// again set change to 2^i
$change = 1 << $i;
}
else
{
$change--;
}
}
// increment the position
$i++;
}
return $ans;
}
// Driver code
$n = 17;
echo(countSetBits($n));
// This code is contributed by Smitha
?>
Output:
35
718
Chapter 116. Count total set bits in all numbers from 1 to n
0|0 0
0|0 1
0|1 0
0|1 1
-|--
1|0 0
1|0 1
1|1 0
The leftmost set bit is in position 2 (positions are considered starting from 0). If we mask
that off what remains is 2 (the “1 0” in the right part of the last row.) So the number of
bits in the 2nd position (the lower left box) is 3 (that is, 2 + 1). The set bits from 0-3 (the
upper right box above) is 2*2^(2-1) = 4. The box in the lower right is the remaining bits
we haven’t yet counted, and is the number of set bits for all the numbers up to 2 (the value
of the last entry in the lower right box) which can be figured recursively.
719
Chapter 116. Count total set bits in all numbers from 1 to n
return m;
}
// The main recursive function used by countSetBits()
unsigned int _countSetBits(unsigned int n, int m);
// Returns count of set bits present in
// all numbers from 1 to n
unsigned int countSetBits(unsigned int n)
{
// Get the position of leftmost set
// bit in n. This will be used as an
// upper bound for next set bit function
int m = getLeftmostBit(n);
// Use the position
return _countSetBits(n, m);
}
unsigned int _countSetBits(unsigned int n, int m)
{
// Base Case: if n is 0, then set bit
// count is 0
if (n == 0)
return 0;
/* get position of next leftmost set bit */
m = getNextLeftmostBit(n, m);
// If n is of the form 2^x-1, i.e., if n
// is like 1, 3, 7, 15, 31, .. etc,
// then we are done.
// Since positions are considered starting
// from 0, 1 is added to m
if (n == ((unsigned int)1 << (m + 1)) - 1)
return (unsigned int)(m + 1) * (1 << m);
// update n for next recursive call
n = n - (1 << m);
return (n + 1) + countSetBits(n) + m * (1 << (m - 1));
}
// Driver program to test above functions
int main()
{
int n = 17;
printf("Total set bit count is %d", countSetBits(n));
return 0;
720
Chapter 116. Count total set bits in all numbers from 1 to n
Time Complexity: O(Logn). From the first look at the implementation, time complexity
looks more. But if we take a closer look, statements inside while loop of getNextLeftmost-
Bit() are executed for all 0 bits in n. And the number of times recursion is executed is
less than or equal to set bits in n. In other words, if the control goes inside while loop of
getNextLeftmostBit(), then it skips those many bits in recursion.
Thanks to agatsu and IC for suggesting this solution.
Here is another solution suggested by Piyush Kapoor.
A simple solution , using the fact that for the ith least significant bit, answer will be
(N/2^i)*2^(i-1)+ X
where
X = N%(2^i)-(2^(i-1)-1)
iff
N%(2^i)>=(2^(i-1)-1)
Source
https://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n/
721
Chapter 117
Input : 8
Output : 3
Binary of 8 is 1000, so there are theree
trailing zero bits.
Input : 18
Output : 1
Binary of 18 is 10010, so there is one
trailing zero bit.
A simple solution is to traverse bits from LSB (Least Significant Bit) and increment
count while bit is 0.
C++
722
Chapter 117. Count trailing zero bits using lookup table
{
int count = 0;
while ((x & 1) == 0)
{
x = x >> 1;
count++;
}
return count;
}
// Driver Code
int main()
{
cout << countTrailingZero(11) << endl;
return 0;
}
Java
723
Chapter 117. Count trailing zero bits using lookup table
C#
PHP
<?php
// Simple PHP code for counting trailing zeros
// in binary representation of a number
function countTrailingZero($x)
{
$count = 0;
while (($x & 1) == 0)
{
$x = $x >> 1;
$count++;
}
return $count;
}
724
Chapter 117. Count trailing zero bits using lookup table
Output :
1. The solution assumes that negative numbers are stored in 2’s complement form which
is true for most of the devices. If numbers are represented in 2’s complement form,
then (x & -x) [Bitwise and of x and minus x] produces a number with only last set bit.
2. Once we get a number with only one bit set, we can find its position using lookup
table. It makes use of the fact that the first 32 bit position values are relatively prime
with 37, so performing a modulus division with 37 gives a unique number from 0 to 36
for each. These numbers may then be mapped to the number of zeros using a small
lookup table.
C++
725
Chapter 117. Count trailing zero bits using lookup table
// Driver Code
int main()
{
cout << countTrailingZero(48) << endl;
return 0;
}
Java
C#
726
Chapter 117. Count trailing zero bits using lookup table
PHP
<?php
// PHP code for counting
// trailing zeros in binary
// representation of a number
function countTrailingZero($x)
{
// Map a bit value mod
// 37 to its position
727
Chapter 117. Count trailing zero bits using lookup table
Output :
Source
https://www.geeksforgeeks.org/count-trailing-zero-bits-using-lookup-table/
728
Chapter 118
Input : n = 42, l = 2, r = 5
Output : 2
(42)10 = (101010)2
There are '2' unset bits in the range 2 to 5.
Input : n = 80, l = 1, r = 4
Output : 4
1. Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number
num having r number of bits and bits in the range l to r are the only set bits.
2. Count number of set bits in the number (n & num). Refer this post. Let it be count.
3. Calculate ans = (r – l + 1) – count.
4. Return ans.
C++
729
Chapter 118. Count unset bits in a range
// Function to get no of set bits in the
// binary representation of 'n'
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
// function to count unset bits
// in the given range
unsigned int countUnsetBitsInGivenRange(unsigned int n,
unsigned int l, unsigned int r)
{
// calculating a number 'num' having 'r' number
// of bits and bits in the range l to r are the
// only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// returns number of unset bits in the range
// 'l' to 'r' in 'n'
return (r - l + 1) - countSetBits(n & num);
}
// Driver program to test above
int main()
{
unsigned int n = 80;
unsigned int l = 1, r = 4;
cout << countUnsetBitsInGivenRange(n, l, r);
return 0;
}
Java
730
Chapter 118. Count unset bits in a range
while (n > 0) {
n &= (n - 1);
count++;
}
return count;
}
// function to count unset bits
// in the given range
static int countUnsetBitsInGivenRange(int n,
int l, int r)
{
// calculating a number 'num' having 'r'
// number of bits and bits in the range
// l to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 <<
(l - 1)) - 1);
// returns number of unset bits in the range
// 'l' to 'r' in 'n'
return (r - l + 1) - countSetBits(n & num);
}
// Driver code
public static void main(String[] args)
{
int n = 80;
int l = 1, r = 4;
System.out.print(
countUnsetBitsInGivenRange(n, l, r));
}
}
// This code is contributed by Anant Agarwal.
Python3
731
Chapter 118. Count unset bits in a range
while n:
n &= (n - 1)
count += 1
return count
# function to count unset bits
# in the given range
def countUnsetBitsInGivenRange (n, l, r):
# calculating a number 'num' having
# 'r' number of bits and bits in the
# range l to r are the only set bits
num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
# returns number of unset bits
# in the range 'l' to 'r' in 'n'
return (r - l + 1) - countSetBits(n & num)
# Driver code to test above
n = 80
l = 1
r = 4
print(countUnsetBitsInGivenRange(n, l, r))
# This code is contributed by "Sharad_Bhardwaj"
C#
732
Chapter 118. Count unset bits in a range
PHP
<?php
// php implementation to count
// unset bits in the given range
// Function to get no of set bits in
// the binary representation of 'n'
function countSetBits($n)
{
$count = 0;
while ($n)
{
$n &= ($n - 1);
$count++;
}
return $count;
}
// function to count unset
733
Chapter 118. Count unset bits in a range
Output:
Source
https://www.geeksforgeeks.org/count-unset-bits-range/
734
Chapter 119
Input : 17
Output : 3
Binary of 17 is 10001
so unset bit is 3
Input : 7
Output : 0
A Simple Solution is to traverse through all bits and count unset bits.
C++
735
Chapter 119. Count unset bits of a number
return count;
}
// Driver code
int main()
{
int n = 17;
cout << countunsetbits(n);
return 0;
}
Java
C#
736
Chapter 119. Count unset bits of a number
PHP
<?php
// PHp program to count
// unset bits in an integer
function countunsetbits($n)
{
$count = 0;
// x holds one set digit
// at a time starting
// from LSB to MSB of n.
for ($x = 1; $x <= $n;
$x = $x << 1)
if (($x & $n) == 0)
$count++;
return $count;
}
// Driver code
$n = 17;
echo countunsetbits($n);
737
Chapter 119. Count unset bits of a number
Output :
738
Chapter 119. Count unset bits of a number
// Driver code
int main()
{
int n = 17;
cout << countUnsetBits(n);
return 0;
}
PHP
<?php
// An optimized PHP program
// to count unset bits in
// an integer.
function countUnsetBits($n)
{
$x = $n;
// Make all bits set
// MSB(including MSB)
// This makes sure two
// bits(From MSB and
// including MSB) are set
$n |= $n >> 1;
// This makes sure 4
// bits(From MSB and
// including MSB) are set
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
$t = log($x ^ $n,2);
// Count set bits
// in toggled number
return floor($t);
}
// Driver code
$n = 17;
echo countUnsetBits($n);
// This code is contributed
739
Chapter 119. Count unset bits of a number
// by ajit
?>
Output :
Source
https://www.geeksforgeeks.org/count-unset-bits-number/
740
Chapter 120
Sender Side (Generation of Encoded Data from Data and Generator Polynomial
(or Key)):
The binary data is first augmented by adding k-1 zeros in the end of the data
Use modulo-2 binary division to divide binary data by the key and store remainder of
division.
Append the remainder at the end of the data to form the encoded data and send the same
.
• In each step, a copy of the divisor (or data) is XORed with the k bits of the dividend
(or key).
• The result of the XOR operation (remainder) is (n-1) bits, which is used for the next
step after 1 extra bit is pulled down to make it n bits long.
741
Chapter 120. Cyclic Redundancy Check and Modulo-2 Division
• When there are no bits left to pull down, we have a result. The (n-1)-bit remainder
which is appended at the sender side.
Illustration:
Example 1 (No error in transmission):
Sender Side:
Receiver Side:
Code word received at the receiver side 100100001
Sender Side:
Receiver Side
Let there be error in transmission media
Code word received at the receiver side - 100000001
Implementation
Below is Python implementation for generating code word from given binary data and key.
742
Chapter 120. Cyclic Redundancy Check and Modulo-2 Division
743
Chapter 120. Cyclic Redundancy Check and Modulo-2 Division
Output:
Remainder : 001
Encoded Data (Data + Remainder) : 100100001
Note that CRC is mainly designed and used to protect against common of errors on commu-
nication channels and NOT suitable protection against intentional alteration of data (See
reasons here)
References:
https://en.wikipedia.org/wiki/Cyclic_redundancy_check
Source
https://www.geeksforgeeks.org/modulo-2-binary-division/
744
Chapter 121
Input : 7
Output : 4
Explanation: 7 is represented as 111 in binary form. The gray code
of 111 is 100 in binary form whose decimal equivalent is 4
Input : 10
Output : 15
Explanation: 10 is represented as 1010 in binary form. The gray code
of 1010 is 1111 in binary form whose decimal equivalent is 15
Following table shows the conversion of binary code values to gray code values:
Decimal Value Binary Equivalent Gray Code Equivalent Decimal Value of Gray Code Equivalent
0 000 000 0
1 001 001 1
2 010 011 3
4 100 110 6
5 101 111 7
6 110 101 5
7 111 100 4
Below is the approach for the conversion of decimal code values to gray code
values.
745
Chapter 121. Decimal Equivalent of Gray Code and its Inverse
Let G(n) be Gray code equivalent of binary represention n. Consider bits of a number n
and a number bit G(n). Note that leftmost set bits of both n and G(n) are at same position.
Let this position be i and positions on right of it be (i+1), (i+2_, etc. The (i + 1)th bit in
G(n) is 0 if i-th bit in n is 1 and vice versa is also true. The same is true for (i+2)-th bits,
etc. Thus we have G (n) = n xor (n >> 1):
C++
Java
746
Chapter 121. Decimal Equivalent of Gray Code and its Inverse
{
int n = 10;
System.out.println(grayCode(n));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python 3
C#
747
Chapter 121. Decimal Equivalent of Gray Code and its Inverse
PHP
<?php
// PHP Program to convert given
// decimal number into decimal
// equivalent of its gray code form
function grayCode($n)
{
/* Right Shift the number by 1
taking xor with original
number */
return $n ^ ($n >> 1);
}
// Driver Code
$n = 10;
echo grayCode($n) ;
// This code is contributed by nitin mittal.
?>
Output:
15
748
Chapter 121. Decimal Equivalent of Gray Code and its Inverse
Input : 4
Output : 7
Input : 15
Output : 10
Below is the approach for the conversion of gray code values to decimal code
values.
We will go from the older bits to the younger ones (even the smallest bit has number 1, and
the oldest bit is numbered k). We obtain such relations between the bits of the ni number
n and the bits of the gi number g:
nk = gk,
nk-1 = gk-1 xor nk = gk xor gk-1
nk-2 = gk-2 xor nk-1 = gk xor gk-1 xor gk-2
nk-3 = gk-3 xor nk-2 = gk xor gk-1 xor gk-2 xor gk-3
...
C++
Java
749
Chapter 121. Decimal Equivalent of Gray Code and its Inverse
Python3
750
Chapter 121. Decimal Equivalent of Gray Code and its Inverse
# Driver Code
n = 15;
print(inversegrayCode(n));
# This code is contributed
# by mits
C#
PHP
<?php
// PHP Program to convert given
// decimal number of gray code
// into its inverse in decimal form
751
Chapter 121. Decimal Equivalent of Gray Code and its Inverse
Output:
10
Improved By : Smitha Dinesh Semwal, jit_t, nitin mittal, vt_m, Mithun Kumar
Source
https://www.geeksforgeeks.org/decimal-equivalent-gray-code-inverse/
752
Chapter 122
Input : 101000
Output : Yes
(101000)2 = (40)10
and 40 is divisible by 10.
Input : 11000111001110
Output : Yes
753
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
754
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
if (sum % 10 == 0)
return true;
// not divisible by 10
return false;
}
// Driver program to test above
int main()
{
string bin = "11000111001110";
if (isDivisibleBy10(bin))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
755
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
{
// if digit in '1'
if (bin.charAt(i) == '1')
{
// calculate digit's position
// from the right
int posFromRight = n - i - 1;
// according to the digit's
// position, obtain the last
// digit of the applicable
// perfect power of 2
if (posFromRight % 4 == 1)
sum = sum + 2;
else if (posFromRight % 4 == 2)
sum = sum + 4;
else if (posFromRight % 4 == 3)
sum = sum + 8;
else if (posFromRight % 4 == 0)
sum = sum + 6;
}
}
// if last digit is 0, then
// divisible by 10
if (sum % 10 == 0)
return true;
// not divisible by 10
return false;
}
/* Driver program to test above function */
public static void main(String[] args)
{
String bin = "11000111001110";
if (isDivisibleBy10(bin))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
756
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
757
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
# divisible by 10
if (sum % 10 == 0) :
return True
# not divisible by 10
return False
# Driver program to test above function
bin = "11000111001110"
if (isDivisibleBy10(bin)== True) :
print("Yes")
else :
print("No")
# This code is contributed by Nikita Tiwari.
C#
758
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
PHP
<?php
// PHP implementation to
759
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
760
Chapter 122. Decimal representation of given binary string is divisible by 10 or not
Output:
Yes
Time Complexity: O(n), where n is the number of digits in the binary number.
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/decimal-representation-given-binary-string-divisible-10-not/
761
Chapter 123
Examples :
Input : 101000
Output : Yes
(10100)2 = (40)10
and 40 is divisible by 20.
Input : 110001110011100
Output : Yes
C++
762
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
763
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
return true;
// not divisible by 10
return false;
}
// function to check whether decimal
// representation of given binary number
// is divisible by 20 or not
bool isDivisibleBy20(char bin[], int n)
{
// if 'bin' is an odd number
if (bin[n - 1] == '1')
return false;
// check if bin(0..n-2) is divisible
// by 10 or not
return isDivisibleBy10(bin, n - 1);
}
// Driver program to test above
int main()
{
char bin[] = "101000";
int n = sizeof(bin) / sizeof(bin[0]);
if (isDivisibleBy20(bin, n - 1))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
764
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
765
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
Python3
766
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
767
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
n = len(bin)
if (isDivisibleBy20(bin, n - 1)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha Dinesh Semwal
C#
768
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
sum = sum + 4;
else if (posFromRight % 4 == 3)
sum = sum + 8;
else if (posFromRight % 4 == 0)
sum = sum + 6;
}
}
// if last digit is 0, then
// divisible by 10
if (sum % 10 == 0)
return true;
// not divisible by 10
return false;
}
// function to check whether decimal
// representation of given binary number
// is divisible by 20 or not
static bool isDivisibleBy20(string bin, int n)
{
// if 'bin' is an odd number
if (bin[n - 1] == '1')
return false;
// check if bin(0..n-2) is divisible
// by 10 or not
return isDivisibleBy10(bin, n - 1);
}
// Driver program to test above
public static void Main()
{
string bin = "101000";
int n = bin.Length;
if (isDivisibleBy20(bin, n - 1))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed
// by vt_m.
769
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
PHP
<?php
// PHP implementation to check whether
// decimal representation of given binary
// number is divisible by 20 or not
// function to check whether decimal
// representation of given binary number
// is divisible by 10 or not
function isDivisibleBy10($bin, $n)
{
// if last digit is '1', then
// number is not divisible by 10
if ($bin[$n - 1] == '1')
return false;
// to accumulate the sum of last
// digits in perfect powers of 2
$sum = 0;
// traverse from the 2nd last up
// to 1st digit in 'bin'
for ($i = $n - 2; $i >= 0; $i--)
{
// if digit in '1'
if ($bin[$i] == '1')
{
// calculate digit's position
// from the right
$posFromRight = $n - $i - 1;
// according to the digit's position,
// obtain the last digit of the
// applicable perfect power of 2
if ($posFromRight % 4 == 1)
$sum = $sum + 2;
else if ($posFromRight % 4 == 2)
$sum = $sum + 4;
else if ($posFromRight % 4 == 3)
$sum = $sum + 8;
else if ($posFromRight % 4 == 0)
$sum = $sum + 6;
}
}
770
Chapter 123. Decimal representation of given binary string is divisible by 20 or not
Output :
Yes
Time Complexity: O(n), where n is the number of digits in the binary number.
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/decimal-representation-given-binary-string-divisible-20-not/
771
Chapter 124
C++
772
Chapter 124. Detect if two integers have opposite signs
Java
Python3
C#
773
Chapter 124. Detect if two integers have opposite signs
// C# Program to Detect
// if two integers have
// opposite signs.
using System;
class GFG {
// Function to detect signs
static bool oppositeSigns(int x, int y)
{
return ((x ^ y) < 0);
}
// Driver Code
public static void Main()
{
int x = 100, y = -100;
if (oppositeSigns(x, y) == true)
Console.Write("Signs are opposite");
else
Console.Write("Signs are not opposite");
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP Program to Detect if two
// integers have opposite signs.
function oppositeSigns($x, $y)
{
return (($x ^ $y) < 0);
}
// Driver Code
$x = 100;
$y = -100;
if (oppositeSigns($x, $y) == true)
echo ("Signs are opposite");
else
echo ("Signs are not opposite");
// This code is contributed by vt_m.
?>
774
Chapter 124. Detect if two integers have opposite signs
Output:
The first method is more efficient. The first method uses a bitwise XOR and a comparison
operator. The second method uses two comparison operators and a bitwise XOR operation
is more efficient compared to a comparison operation.
We can also use following method. It doesn’t use any comparison operator. The method is
suggested by Hongliang and improved by gaurav.
The function is written only for compilers where size of an integer is 32 bit. The expression
basically checks sign of (x^y) using bitwise operator ‘>>’. As mentioned above, the sign bit
for negative numbers is always 1. The sign bit is the leftmost bit in binary representation.
So we need to checks whether the 32th bit (or leftmost bit) of x^y is 1 or not. We do it by
right shifting the value of x^y by 31, so that the sign bit becomes the least significant bit.
If sign bit is 1, then the value of (x^y)>>31 will be 1, otherwise 0.
Improved By : nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/detect-if-two-integers-have-opposite-signs/
775
Chapter 125
Input : abcd10jk
Output : true
Input : hutg9mnd!nk9
Output : false
Approach 1 – Brute Force technique: Run 2 loops with variable i and j. Compare
str[i] and str[j]. If they become equal at any point, return false.
Time Complexity: O(n2 )
C++
776
Chapter 125. Determine if a string has all Unique Characters
Java
777
Chapter 125. Determine if a string has all Unique Characters
C#
778
Chapter 125. Determine if a string has all Unique Characters
PHP
<?php
// PHP program to illustrate string
// with unique characters using
// brute force technique
function uniqueCharacters($str)
{
// If at any time we encounter 2
// same characters, return false
for($i = 0; $i < strlen($str); $i++)
{
for($j = $i + 1; $j < strlen($str); $j++)
{
if($str[$i] == $str[$j])
{
return false;
}
}
}
// If no duplicate characters
// encountered, return true
return true;
}
// Driver Code
$str = "GeeksforGeeks";
if(uniqueCharacters($str))
{
echo "The String ", $str,
" has all unique characters\n";
}
else
{
echo "The String ", $str,
" has duplicate characters\n";
}
779
Chapter 125. Determine if a string has all Unique Characters
// This code is contributed by ajit
?>
Output :
C++
780
Chapter 125. Determine if a string has all Unique Characters
Java
781
Chapter 125. Determine if a string has all Unique Characters
C#
782
Chapter 125. Determine if a string has all Unique Characters
if (uniqueCharacters(input) == true)
Console.WriteLine("The String " + input
+ " has all unique characters");
else
Console.WriteLine("The String " + input
+ " has duplicate characters");
}
}
// This code is contributed by shiv_bhakt.
Output:
Approach 3 – Use of Extra Data Structure: This approach assumes ASCII char set(8
bits). The idea is to maintain a boolean array for the characters. The 256 indices represent
256 characters. All the array elements are initially set to false. As we iterate over the string,
set true at the index equal to the int value of the character. If at any time, we encounter
that the array value is already true, it means the character with that int value is repeated.
Time Complexity: O(n)
C++
#include <cstring>
#include <iostream>
using namespace std;
const int MAX_CHAR = 256;
bool uniqueCharacters(string str)
{
// If length is greater than 265,
// some characters must have been repeated
if (str.length() > MAX_CHAR)
return false;
bool chars[MAX_CHAR] = { 0 };
for (int i = 0; i < str.length(); i++) {
if (chars[int(str[i])] == true)
return false;
chars[int(str[i])] = true;
783
Chapter 125. Determine if a string has all Unique Characters
}
return true;
}
// driver code
int main()
{
string str = "GeeksforGeeks";
if (uniqueCharacters(str)) {
cout << "The String " << str
<< " has all unique characters\n";
}
else {
cout << "The String " << str
<< " has duplicate characters\n";
}
return 0;
}
// This code is contributed by Divyam Madaan
Java
784
Chapter 125. Determine if a string has all Unique Characters
chars[index] = true;
}
/* No duplicates encountered, return true */
return true;
}
// Driver code
public static void main(String args[])
{
GfG obj = new GfG();
String input = "GeeksforGeeks";
if (obj.uniqueCharacters(input))
System.out.println("The String " + input
+ " has all unique characters");
else
System.out.println("The String " + input
+ " has duplicate characters");
}
}
Output:
Approach 4 – Without Extra Data Structure: The approach is valid for strings having
alphabet as a-z. This approach is little tricky. Instead of maintaining a boolean array, we
maintain an integer value called checker(32 bits). As we iterate over the string, we find
the int value of the character with respect to ‘a’ with the statement int bitAtIndex =
str.charAt(i)-‘a’;
Then the bit at that int value is set to 1 with the statement 1 << bitAtIndex .
Now, if this bit is already set in the checker, the bit AND operation would make checker >
0. Return false in this case.
Else Update checker to make the bit 1 at that index with the statement checker = checker
| (1 <<bitAtIndex);
Time Complexity: O(n)
C++
785
Chapter 125. Determine if a string has all Unique Characters
bool uniqueCharacters(string str)
{
// Assuming string can have characters
// a-z, this has 32 bits set to 0
int checker = 0;
for (int i = 0; i < str.length(); i++) {
int bitAtIndex = str[i] - 'a';
// if that bit is already set in
// checker, return false
if ((checker & (1 << bitAtIndex)) > 0) {
return false;
}
// otherwise update and continue by
// setting that bit in the checker
checker = checker | (1 << bitAtIndex);
}
// no duplicates encountered, return true
return true;
}
// driver code
int main()
{
string str = "GeeksforGeeks";
if (uniqueCharacters(str)) {
cout << "The String " << str
<< " has all unique characters\n";
}
else {
cout << "The String " << str
<< " has duplicate characters\n";
}
return 0;
}
// This code is contributed by Divyam Madaan
Java
786
Chapter 125. Determine if a string has all Unique Characters
PHP
<?php
// PHP program to illustrate
// string with unique characters
// using brute force technique
787
Chapter 125. Determine if a string has all Unique Characters
function uniqueCharacters($str)
{
// Assuming string can have
// characters a-z, this has
// 32 bits set to 0
$checker = 0;
for ($i = 0; $i < strlen($str); $i++)
{
$bitAtIndex = $str[$i] - 'a';
// if that bit is already set
// in checker, return false
if (($checker &
(1 << $bitAtIndex)) > 0)
{
return false;
}
// otherwise update and continue by
// setting that bit in the checker
$checker = $checker |
(1 << $bitAtIndex);
}
// no duplicates encountered,
// return true
return true;
}
// Driver Code
$str = "GeeksforGeeks";
if(uniqueCharacters($str))
{
echo "The String ", $str,
" has all unique characters\n";
}
else
{
echo "The String ", $str,
" has duplicate characters\n";
}
// This code is contributed by ajit
?>
788
Chapter 125. Determine if a string has all Unique Characters
Output :
Exercise : Above program is case sensitive, you can try making same program which is
case insensitive i.e Geeks and GEeks both give similar output.
Reference:
Cracking the Coding Interview by Gayle
Improved By : shiv_bhakt, jit_t, V1
Source
https://www.geeksforgeeks.org/determine-string-unique-characters/
789
Chapter 126
Approach :We can find solution by simply running DFS on tree. DFS solution gives us
answer in O(n). But, how can we use DSU for this problem? We first iterate through all
790
Chapter 126. Disjoint Set Union on trees | Set 1
edges. If both nodes are even in weights, we make union of them. Set of nodes with maximum
size is the answer. If we use union-find with path compression then time complexity is O(n).
Below is the implementation of above approach :
791
Chapter 126. Disjoint Set Union on trees | Set 1
{
id[i] = j, sz[j] += sz[i];
sz[i] = 0;
}
}
}
// Utility function for Union
void UnionUtil(struct Edge e[], int W[], int q)
{
for(int i = 0; i < q; i++)
{
// Edge between 'u' and 'v'
int u, v;
u = e[i].u, v = e[i].v;
// 0-indexed nodes
u--, v--;
// If weights of both 'u' and 'v'
// are even then we make union of them.
if(W[u] % 2 == 0 && W[v] % 2 == 0)
Union(u,v);
}
}
// Function to find maximum
// size of DSU tree
int findMax(int n, int W[])
{
int maxi = 0;
for(int i = 1; i <= n; i++)
if(W[i] % 2 == 0)
maxi = max(maxi, sz[i]);
return maxi;
}
// Driver code
int main()
{
/*
Nodes are 0-indexed in this code
So we have to make necessary changes
while taking inputs
*/
792
Chapter 126. Disjoint Set Union on trees | Set 1
Output:
Source
https://www.geeksforgeeks.org/disjoint-set-union-trees-set-1/
793
Chapter 127
Approach : The strategy is to fix the AND, and find the maximum size of a subtree such
that AND of all indices equals to the given AND. Suppose we fix AND as ‘A’. In binary
representation of A, if the ith bit is ‘1’, then all indices(nodes) of the required subtree should
have ‘1’ in ith position in binary representation. If ith bit is ‘0’ then indices either have ‘0’
or ‘1’ in ith position. That means all elements of subtree are super masks of A. All super
masks of A can be generated in O(2^k) time where ‘k’ is the number of bits which are ‘0’
in A.
794
Chapter 127. Disjoint Set Union on trees | Set 2
Now, the maximum size of subtree with a given AND ‘A’ can be found using DSU on the
tree. Let, ‘u’ be the super mask of A and ‘p[u]’ be the parent of u. If p[u] is also a super
mask of A, then, we have to update the DSU by merging the components of u and p[u].
Simultaneously, we also have to keep track of the maximum size of subtree. DSU helps us
to do it. It will be more clear if we look at following code.
795
Chapter 127. Disjoint Set Union on trees | Set 2
else {
id[i] = j, sz[j] += sz[i];
sz[i] = 0;
}
}
}
};
wunionfind W;
// DFS is called to generate parent of
// a node from adjacency list representation
void dfs(int u, int parent)
{
for (int i = 0; i < v[u].size(); i++) {
int j = v[u][i];
if (j != parent) {
p[j] = u;
dfs(j, u);
}
}
}
// Utility function for Union
int UnionUtil(int n)
{
int ans = 0;
// Fixed 'i' as AND
for (int i = 1; i <= n; i++) {
int maxi = 1;
// Generating supermasks of 'i'
for (int x = i; x <= n; x = (i | (x + 1))) {
int y = p[x];
// Checking whether p[x] is
// also a supermask of i.
if ((y & i) == i) {
W.Union(x, y);
// Keep track of maximum
// size of subtree
maxi = max(maxi, W.sz[W.Root(x)]);
}
}
// Storing maximum cost of
796
Chapter 127. Disjoint Set Union on trees | Set 2
797
Chapter 127. Disjoint Set Union on trees | Set 2
return 0;
}
Output:
Maximum Cost = 8
Time Complexity : Union in DSU takes O(1) time. Generating all supermasks takes
O(3^k) time where k is the maximum number of bits which are ‘0’. DFS takes O(n). Overall
time complexity is O(3^k+n).
Source
https://www.geeksforgeeks.org/disjoint-set-union-trees-set-2/
798
Chapter 128
Divide two integers without using multiplication, division and mod operator - GeeksforGeeks
Given a two integers say a and b. Find the quotient after dividing a by b without using
multiplication, division and mod operator.
Example:
Input : a = 10, b = 3
Output : 3
Input : a = 43, b = -8
Output : -5
Approach : Keep subtracting the divisor from dividend until dividend becomes less than
divisor. The dividend becomes the remainder, and the number of times subtraction is done
becomes the quotient. Below is the implementation of above approach :
C++
799
Chapter 128. Divide two integers without using multiplication, division and mod operator
Java
800
Chapter 128. Divide two integers without using multiplication, division and mod operator
{
// Calculate sign of divisor i.e.,
// sign will be negative only iff
// either one of them is negative
// otherwise it will be positive
int sign = ((dividend < 0) ^
(divisor < 0)) ? -1 : 1;
// Update both divisor and
// dividend positive
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
// Initialize the quotient
int quotient = 0;
while (dividend >= divisor)
{
dividend -= divisor;
++quotient;
}
return sign * quotient;
}
public static void main (String[] args)
{
int a = 10;
int b = 3;
System.out.println(divide(a, b));
a = 43;
b = -8;
System.out.println(divide(a, b));
}
}
// This code is contributed by upendra singh bartwal.
Python3
801
Chapter 128. Divide two integers without using multiplication, division and mod operator
C#
802
Chapter 128. Divide two integers without using multiplication, division and mod operator
{
// Calculate sign of divisor i.e.,
// sign will be negative only iff
// either one of them is negative
// otherwise it will be positive
int sign = ((dividend < 0) ^
(divisor < 0)) ? -1 : 1;
// Update both divisor and
// dividend positive
dividend = Math.Abs(dividend);
divisor = Math.Abs(divisor);
// Initialize the quotient
int quotient = 0;
while (dividend >= divisor)
{
dividend -= divisor;
++quotient;
}
return sign * quotient;
}
public static void Main ()
{
int a = 10;
int b = 3;
Console.WriteLine(divide(a, b));
a = 43;
b = -8;
Console.WriteLine(divide(a, b));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP implementation to Divide two
// integers without using multiplication,
// division and mod operator
803
Chapter 128. Divide two integers without using multiplication, division and mod operator
Output :
3
-5
804
Chapter 128. Divide two integers without using multiplication, division and mod operator
Efficient Approach : Use bit manipulation in order to find the quotient. The divisor and
dividend can be written as
As every number can be represented in base 2(0 or 1), represent the quotient in binary form
by using shift operator as given below :
1. Determine the most significant bit in the quotient. This can easily be calculated by
iterating on the bit position i from 31 to 1.
2. Find the first bit for which is less than dividend and keep
updating the ith bit position for which it is true.
3. Add the result in temp variable for checking the next position such that (temp +
(divisor << i) ) is less than dividend.
4. Return the final answer of quotient after updating with corresponding sign.
C++
805
Chapter 128. Divide two integers without using multiplication, division and mod operator
Java
806
Chapter 128. Divide two integers without using multiplication, division and mod operator
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
// Initialize the quotient
long quotient = 0, temp = 0;
// test down from the highest
// bit and accumulate the
// tentative value for
// valid bit
for (int i = 31; i >= 0; --i)
{
if (temp + (divisor << i) <= dividend)
{
temp += divisor << i;
quotient |= 1 << i;
}
}
return (sign * quotient);
}
// Driver code
public static void main(String args[])
{
int a = 10, b = 3;
System.out.println(divide(a, b));
int a1 = 43, b1 = -8;
System.out.println(divide(a1, b1));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Python3
# Python3 implementation to
# Divide two integers
# without using multiplication,
# division and mod operator
# Function to divide a by
# b and return floor value it
def divide(dividend, divisor):
# Calculate sign of divisor
807
Chapter 128. Divide two integers without using multiplication, division and mod operator
// C# implementation to Divide
// two integers without using
// multiplication, division
// and mod operator
using System;
// Function to divide a by b
// and return floor value it
class GFG
{
public static long divide(long dividend,
long divisor)
{
// Calculate sign of divisor
// i.e., sign will be negative
// only iff either one of them
// is negative otherwise it
// will be positive
long sign = ((dividend < 0) ^
(divisor < 0)) ? -1 : 1;
// remove sign of operands
dividend = Math.Abs(dividend);
divisor = Math.Abs(divisor);
// Initialize the quotient
long quotient = 0, temp = 0;
// test down from the highest
// bit and accumulate the
// tentative value for
// valid bit
for (int i = 31; i >= 0; --i)
{
if (temp + (divisor << i) <= dividend)
808
Chapter 128. Divide two integers without using multiplication, division and mod operator
{
temp += divisor << i;
quotient |= 1LL << i;
}
}
return (sign * quotient);
}
// Driver code
public static void Main()
{
int a = 10, b = 3;
Console.WriteLine(divide(a, b));
int a1 = 43, b1 = -8;
Console.WriteLine(divide(a1, b1));
}
}
// This code is contributed by mits
PHP
<?php
// PHP implementation to
// Divide two integers
// without using multiplication,
// division and mod operator
// Function to divide a by
// b and return floor value it
function divide($dividend,
$divisor)
{
// Calculate sign of divisor
// i.e., sign will be negative
// either one of them is negative
// only iff otherwise it will be
// positive
$sign = (($dividend < 0) ^
($divisor < 0)) ? -1 : 1;
// remove sign of operands
$dividend = abs($dividend);
$divisor = abs($divisor);
809
Chapter 128. Divide two integers without using multiplication, division and mod operator
// Initialize
// the quotient
$quotient = 0;
$temp = 0;
// test down from the highest
// bit and accumulate the
// tentative value for valid bit
for ($i = 31; $i >= 0; --$i)
{
if ($temp + ($divisor << $i) <= $dividend)
{
$temp += $divisor << $i;
$quotient |= (double)(1) << $i;
}
}
return $sign * $quotient;
}
// Driver code
$a = 10;
$b = 3;
echo divide($a, $b). "\n";
$a = 43;
$b = -8;
echo divide($a, $b);
// This code is contributed by mits
?>
Output :
3
-5
Source
https://www.geeksforgeeks.org/divide-two-integers-without-using-multiplication-division-mod-operator/
810
Chapter 129
Input: 100010001
Output: Possible
Explanation: We can get string 1 000 000
after removing two ones which is a
representation of number 64 in the binary
numerical system.
Input: 100
Output: Not possible
Explanation : The number is 4 which is not
divisible by 64 or cannot be made possible
my removing some digits.
If we have 6 zeros after any one, then we can remove other bits represent it as a multiple
of 64. So we just need to check if there is a 1 before six zeros.
C++
811
Chapter 129. Divisibility by 64 with removal of bits allowed
#include <iostream>
using namespace std;
// function to check if it is possible
// to make it a multiple of 64.
bool checking(string s)
{
int c = 0; // counter to count 0's
int n = s.length(); // length of the string
// loop which traverses right to left and
// calculates the number of zeros before 1.
for (int i = n - 1; i >= 0; i--) {
if (s[i] == '0')
c++;
if (c >= 6 and s[i] == '1')
return true;
}
return false;
}
// driver code
int main()
{
string s = "100010001";
if (checking(s))
cout << "Possible";
else
cout << "Not possible";
return 0;
}
Java
812
Chapter 129. Divisibility by 64 with removal of bits allowed
C#
813
Chapter 129. Divisibility by 64 with removal of bits allowed
PHP
<?php
// PHP program to find if
// given binary string can
// become divisible by 64
// after removing some bits.
// function to check if
// it is possible
// to make it a multiple of 64.
814
Chapter 129. Divisibility by 64 with removal of bits allowed
function checking($s)
{
// counter to count 0's
$c = 0;
// length of the string
$n = strlen($s);
// loop which traverses right
// to left and calculates the
// number of zeros before 1.
for ($i = $n - 1; $i >= 0; $i--)
{
if ($s[$i] == '0')
$c++;
if ($c >= 6 and $s[$i] == '1')
return true;
}
return false;
}
// Driver Code
$s = "100010001";
if (checking($s))
echo "Possible";
else
echo "Not possible";
// This code is contributed by ajit
?>
Output :
Possible
Source
https://www.geeksforgeeks.org/divisibility-64-removal-bits-allowed/
815
Chapter 130
816
Chapter 130. Efficient method for 2’s complement of a binary string
C++
817
Chapter 130. Efficient method for 2’s complement of a binary string
{
string str = "00000101";
cout << findTwoscomplement(str);
return 0;
}
Java
818
Chapter 130. Efficient method for 2’s complement of a binary string
System.out.println(findTwoscomplement(str));
}
}
PHP
<?php
// An efficient PHP program to find 2's
// complement
// Function to find two's complement
function findTwoscomplement($str)
{
$n = strlen($str);
// Traverse the string to get first
// '1' from the last of string
$i;
for ($i = $n-1 ; $i >= 0 ; $i--)
if ($str[$i] == '1')
break;
// If there exists no '1' concatenate
// 1 at the starting of string
if ($i == -1)
return '1' + $str;
// Continue traversal after the
// position of first '1'
for ($k = $i-1 ; $k >= 0; $k--)
{
// Just flip the values
if ($str[$k] == '1')
$str[$k] = '0';
else
$str[$k] = '1';
}
// return the modified string
return $str;;
}
// Driver code
$str = "00000101";
echo findTwoscomplement($str);
// This code is contributed by jit.
?>
819
Chapter 130. Efficient method for 2’s complement of a binary string
Output:
11111011
Source
https://www.geeksforgeeks.org/efficient-method-2s-complement-binary-string/
820
Chapter 131
Program:
# include<stdio.h>
int multiplyBySeven(unsigned int n)
{
/* Note the inner bracket here. This is needed
because precedence of '-' operator is higher
than '<<' */
return ((n<<3) - n);
}
/* Driver program to test above function */
int main()
{
unsigned int n = 4;
printf("%u", multiplyBySeven(n));
getchar();
return 0;
}
Java
821
Chapter 131. Efficient way to multiply with 7
Python
C#
822
Chapter 131. Efficient way to multiply with 7
// positive number to 7
using System;
class GFG
{
static int multiplyBySeven(int n)
{
/* Note the inner bracket here. This is needed
because precedence of '-' operator is higher
than '<<' */
return ((n << 3) - n);
}
// Driver code
public static void Main ()
{
int n = 4;
Console.Write(multiplyBySeven(n));
}
}
// This code is contributed by Sam007
PHP
<?php
function multiplyBySeven($n)
{
// Note the inner bracket here.
// This is needed because
// precedence of '-' operator
// is higherthan '<<'
return (($n<<3) - $n);
}
// Driver Code
$n = 4;
echo multiplyBySeven($n);
// This code is contributed by vt_m.
?>
Output:
28
823
Chapter 131. Efficient way to multiply with 7
Source
https://www.geeksforgeeks.org/efficient-way-to-multiply-with-7/
824
Chapter 132
Efficiently check if a string has duplicates without using any additional data structure -
GeeksforGeeks
Implement an space efficient algorithm to determine if a string (of characters from ‘a’ to ‘z’)
has all unique characters or not. Use additional data structures like count array, hash, etc
is not allowed.
Expected Time Complexity : O(n)
Examples :
The idea is to use an integer variable and use bits in its binary representation to store
whether a character is present or not. Typically an integer has at-least 32 bits and we need
to store presence/absence of only 26 characters.
Below is the implementation of the idea.
C++
825
Chapter 132. Efficiently check if a string has duplicates without using any additional data
structure
Java
826
Chapter 132. Efficiently check if a string has duplicates without using any additional data
structure
// unique.
// Assumptions : (1) str contains only characters
// from 'a' to 'z'
// (2) integers are stored using 32
// bits
static boolean areChractersUnique(String str)
{
// An integer to store presence/absence
// of 26 characters using its 32 bits.
int checker = 0;
for (int i = 0; i < str.length(); ++i)
{
int val = (str.charAt(i)-'a');
// If bit corresponding to current
// character is already set
if ((checker & (1 << val)) > 0)
return false;
// set bit in checker
checker |= (1 << val);
}
return true;
}
//driver code
public static void main (String[] args)
{
String s = "aaabbccdaa";
if (areChractersUnique(s))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Anant Agarwal.
C#
827
Chapter 132. Efficiently check if a string has duplicates without using any additional data
structure
class GFG {
// Returns true if all characters
// of str are unique. Assumptions:
// (1)str contains only characters
// from 'a' to 'z'.(2)integers are
// stored using 32 bits
static bool areChractersUnique(string str)
{
// An integer to store presence
// or absence of 26 characters
// using its 32 bits.
int checker = 0;
for (int i = 0; i < str.Length; ++i) {
int val = (str[i] - 'a');
// If bit corresponding to current
// character is already set
if ((checker & (1 << val)) > 0)
return false;
// set bit in checker
checker |= (1 << val);
}
return true;
}
// Driver code
public static void Main()
{
string s = "aaabbccdaa";
if (areChractersUnique(s))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// A space efficient PHP program
828
Chapter 132. Efficiently check if a string has duplicates without using any additional data
structure
Output :
No
829
Chapter 132. Efficiently check if a string has duplicates without using any additional data
structure
Source
https://www.geeksforgeeks.org/efficiently-check-string-duplicates-without-using-additional-data-structure/
830
Chapter 133
Input : 16
Output : Yes
Input : 14
Output : No
Approach: A multiple of 4 always has 00 as its last two digits in its binary representation.
We have to check whether the last two digits of n are unset or not.
How to check whether the last two bits are unset or not.
If n & 3 == 0, then the last two bits are unset, else either both or one of them are set.
C/C++
831
Chapter 133. Efficiently check whether n is a multiple of 4 or not
Java
C#
832
Chapter 133. Efficiently check whether n is a multiple of 4 or not
class GFG {
// method to check whether 'n' is
// a multiple of 4 or not
static bool isAMultipleOf4(int n)
{
// if true, then 'n' is a multiple of 4
if ((n & 3) == 0)
return true;
// else 'n' is not a multiple of 4
return false;
}
// Driver method
public static void Main()
{
int n = 16;
Console.WriteLine(isAMultipleOf4(n) ? "Yes" : "No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP implementation to
// efficiently check whether n
// is a multiple of 4 or not
// function to check whether 'n' is
// a multiple of 4 or not
function isAMultipleOf4($n)
{
// if true, then 'n'
// is a multiple of 4
if (($n & 3) == 0)
return "Yes";
// else 'n' is not
// a multiple of 4
return "No";
}
// Driver Code
833
Chapter 133. Efficiently check whether n is a multiple of 4 or not
$n = 16;
echo isAMultipleOf4($n);
// This code is contributed by anuj_67.
?>
Output:
Yes
Improved By : vt_m
Source
https://www.geeksforgeeks.org/efficiently-check-whether-n-multiple-4-not/
834
Chapter 134
Efficiently find first repeated character in a string without using any additional data struc-
ture in one traversal - GeeksforGeeks
Implement a space efficient algorithm to check First repeated character in a string without
using any additional data structure in one traversal. Use additional data structures like
count array, hash, etc is not allowed.
Examples :
Input : abcfdeacf
Output : char = a, index= 6
The idea is to use an integer variable and uses bits in its binary representation to store
whether a character is present or not. Typically an integer has at-least 32 bits and we need
to store presence/absence of only 26 characters.
C++
835
Chapter 134. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
// unique.
// Assumptions : (1) str contains only characters
// from 'a' to 'z'
// (2) integers are stored using 32
// bits
int FirstRepeated(string str)
{
// An integer to store presence/absence
// of 26 characters using its 32 bits.
int checker = 0;
for (int i = 0; i < str.length(); ++i)
{
int val = (str[i]-'a');
// If bit corresponding to current
// character is already set
if ((checker & (1 << val)) > 0)
return i;
// set bit in checker
checker |= (1 << val);
}
return -1;
}
// Driver code
int main()
{
string s = "abcfdeacf";
int i=FirstRepeated(s);
if (i!=-1)
cout <<"Char = "<< s[i] << " and Index = "<<i;
else
cout << "No repeated Char";
return 0;
}
Java
836
Chapter 134. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
Python
837
Chapter 134. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
pos = 0
for i in string:
val = ord(i) - ord('a');
# If bit corresponding to current
# character is already set
if ((checker & (1 << val)) > 0):
return pos
# set bit in checker
checker |= (1 << val)
pos += 1
return -1
# Driver code
string = "abcfdeacf"
i = FirstRepeated(string)
if i != -1:
print "Char = ", string[i], " and Index = ", i;
else:
print "No repeated Char"
# This code is contributed by Sachin Bisht
C#
// C# program to Efficiently
// check First repeated character
using System;
public class First_Repeated_char {
static int FirstRepeated(string str)
{
// An integer to store presence/absence
// of 26 characters using its 32 bits.
int checker = 0;
for (int i = 0; i < str.Length; ++i)
{
int val = (str[i]-'a');
// If bit corresponding to current
// character is already set
if ((checker & (1 << val)) > 0)
return i;
838
Chapter 134. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
// set bit in checker
checker |= (1 << val);
}
return -1;
}
// Driver code
public static void Main()
{
string s = "abcfdeacf";
int i=FirstRepeated(s);
if (i!=-1)
Console.WriteLine("Char = " + s[i] +
" and Index = " + i);
else
Console.WriteLine( "No repeated Char");
}
}
// This code is contributed by vt_m.
Output:
Source
https://www.geeksforgeeks.org/efficiently-find-first-repeated-character-string-without-using-additional-data-structu
839
Chapter 135
Input : n = 7
Output : 1
Explanation:
7^i = 7+i holds only for only for i = 0
7+0 = 7^0 = 7
Input n = 12
Output: 4
12^i = 12+i hold only for i = 0, 1, 2, 3
for i=0, 12+0 = 12^0 = 12
for i=1, 12+1 = 12^1 = 13
for i=2, 12+2 = 12^2 = 14
for i=3, 12+3 = 12^3 = 15
Method 1 (Simple) :
One simple solution is to iterate over all values of i 0<= i <= n and count all satisfying
values.
C++
840
Chapter 135. Equal Sum and XOR
Java
841
Chapter 135. Equal Sum and XOR
return countV;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 12;
System.out.println(countValues(n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
842
Chapter 135. Equal Sum and XOR
using System;
class GFG {
// function to count number of values
// less than equal to n that satisfy
// the given condition
public static int countValues (int n)
{
int countV = 0;
// Traverse all numbers from 0 to n
// and increment result only when
// given condition is satisfied.
for (int i = 0; i <= n; i++ )
if ((n + i) == (n ^ i) )
countV++;
return countV;
}
/* Driver program to test above function */
public static void Main()
{
int n = 12;
Console.WriteLine(countValues(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to print count
// of values such that n+i = n^i
// function to count number
// of values less than
// equal to n that satisfy
// the given condition
function countValues ($n)
{
$countV = 0;
// Traverse all numbers
// from 0 to n and
843
Chapter 135. Equal Sum and XOR
Output:
Method 2 (Efficient) :
An efficient solution is as follows
Since we know a + b = a ^ b + 2 * (a & b)
We can write, n + i = n ^ i + 2 * (n & i)
So n + i = n ^ i implies n & i = 0
Hence our problem reduces to finding values of i such that n & i = 0. How to find count of
such pairs? We can use the count of unset-bits in the binary representation of n. For n & i
to be zero, i must unset all set-bits of n. If the kth bit is set at a particular in n, kth bit in
i must be 0 always, else kth bit of i can be 0 or 1
Hence, total such combinations are 2^(count of unset bits in n)
For example, consider n = 12 (Binary representation : 1 1 0 0).
All possible values of i that can unset all bits of n are 0 0 0/1 0/1 where 0/1 implies either
0 or 1. Number of such values of i are 2^2 = 4.
The following is the program following the above idea.
C++
844
Chapter 135. Equal Sum and XOR
// function to count number of values less than
// equal to n that satisfy the given condition
int countValues(int n)
{
// unset_bits keeps track of count of un-set
// bits in binary representation of n
int unset_bits=0;
while (n)
{
if ((n & 1) == 0)
unset_bits++;
n=n>>1;
}
// Return 2 ^ unset_bits
return 1 << unset_bits;
}
// Driver code
int main()
{
int n = 12;
cout << countValues(n);
return 0;
}
Java
845
Chapter 135. Equal Sum and XOR
n=n>>1;
}
// Return 2 ^ unset_bits
return 1 << unset_bits;
}
/* Driver program to test above
function */
public static void main(String[] args)
{
int n = 12;
System.out.println(countValues(n));
}
}
// This code is contributed by Arnav Kr. Mandal.
C#
846
Chapter 135. Equal Sum and XOR
PHP
<?php
/* PHP program to print count
of values such that n+i = n^i */
// function to count number of
// values less than equal to n
// that satisfy the given
// condition
function countValues( $n)
{
// unset_bits keeps track
// of count of un-set bits
// in binary representation
// of n
$unset_bits = 0;
while ($n)
{
if (($n & 1) == 0)
$unset_bits++;
$n = $n >> 1;
}
// Return 2 ^ unset_bits
return 1 << $unset_bits;
}
// Driver code
$n = 12;
echo countValues($n);
// This code is contributed
// by Anuj_67.
?>
847
Chapter 135. Equal Sum and XOR
Output :
Source
https://www.geeksforgeeks.org/equal-sum-xor/
848
Chapter 136
849
Chapter 136. Euclid’s Algorithm when % and / operations are costly
numbers is much bigger than the other. Version 2 is obviously more efficient as there are
less recursive calls and takes logarithmic time.
Consider a situation where modulo operator is not allowed, can we optimize
version 1 to work faster?
Below are some important observations. The idea is to use bitwise operators. We can find
x/2 using x>>1. We can check whether x is odd or even using x&1.
gcd(a, b) = 2*gcd(a/2, b/2) if both a and b are even.
gcd(a, b) = gcd(a/2, b) if a is even and b is odd.
gcd(a, b) = gcd(a, b/2) if a is odd and b is even.
Below is C++ implementation.
This article is compiled by Shivam Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/euclids-algorithm-when-and-operations-are-costly/
850
Chapter 137
Input : number = 72
k = 5
p = 1
Output : The extracted number is 8
72 is represented as 1001000 in binary,
so, you should get only 01000 i.e 8.
851
Chapter 137. Extract ‘k’ bits from a given position in a number.
#include <stdio.h>
// Function to extract k bits from p position
// and returns the extracted value as integer
int bitExtracted(int number, int k, int p)
{
return (((1 << k) - 1) & (number >> (p - 1)));
}
// Driver code
int main()
{
int number = 171, k = 5, p = 2;
printf("The extracted number is %d",
bitExtracted(number, k, p));
return 0;
}
Java
Python
852
Chapter 137. Extract ‘k’ bits from a given position in a number.
C#
PHP
<?php
//PHP program to extract
// k bits from a given
// position.
// Function to extract k
// bits from p position
// and returns the extracted
853
Chapter 137. Extract ‘k’ bits from a given position in a number.
// value as integer
function bitExtracted($number, $k, $p)
{
return (((1 << $k) - 1) &
($number >> ($p - 1)));
}
// Driver Code
$number = 171; $k = 5; $p = 2;
echo "The extracted number is ",
bitExtracted($number, $k, $p);
// This code is contributed by Ajit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/extract-k-bits-given-position-number/
854
Chapter 138
Input : x = 10, y = 12
Output : 11
Input : x = 10, y = 7
Output : 8
We take floor of sum.
The idea is to use right shift operator, instead of doing (x + y)/2, we do (x + y) >> 1
855
Chapter 138. Fast average of two numbers without division
Java
Python3
C#
856
Chapter 138. Fast average of two numbers without division
PHP
<?php
// PHP program to find average
// without using division.
// function returns
// the average
function floorAvg($x, $y)
{
return ($x + $y) >> 1;
}
// Driver Code
$x = 10;
$y = 20;
echo "Average = ", floorAvg($x, $y);
// This Code is contributed by Ajit
?>
Output:
Average = 15
Applications :
We need floor of average of two numbers in many standard algorithms like Merge Sort,Binary
Search, etc. Since we use bitwise operator instead of division, the above way of finding
average is faster.
Improved By : parashar, Dildar_Sk, jit_t
Source
https://www.geeksforgeeks.org/fast-average-two-numbers-without-division/
857
Chapter 139
Fast inverse square root is an algorithm that estimates , the reciprocal (or multiplica-
tive inverse) of the square root of a 32-bit floating-point number x in IEEE 754 floating-point
format. Computing reciprocal square roots is necessary in many applications, such as vector
normalization in video games and is mostly used in calculations involved in 3D programming.
In 3D graphics, surface normals, 3-coordinate vectors of length 1 is used, to express lighting
and reflection. There were a lot of surface normals. And calculating them involves normal-
izing a lot of vectors. Normalizing is often just a fancy term for division. The Pythagorean
theorem computes distance between points, and dividing by distance helps normalize vec-
tors:
This algorithm is best known for its implementation in 1999 in the source code of Quake
III Arena Game, a first-person shooter video game that made heavy use of 3D graphics.
At that time, it was generally computationally expensive to compute the reciprocal of a
floating-point number, especially on a large scale; the fast inverse square root bypassed this
step.
Algorithm :
Step 1 : It reinterprets the bits of the floating-point input as an integer.
i = * ( long * ) &y;
Step 2 : It takes the resulting value and does integer arithmetic on it which produces an
approximation of the value we’re looking for.
858
Chapter 139. Fast inverse square root
i = 0x5f3759df - ( i >> 1 );
Step 3 : The result is not the approximation itself though, it is an integer which happens
to be, if you reinterpret the bits as a floating point number, the approximation. So the code
does the reverse of the conversion in step 1 to get back to floating point:
y = * ( float * ) &i;
Step 4 : And finally it runs a single iteration of Newton’s method to improve the approxi-
mation.
The algorithm accepts a 32-bit floating-point number as the input and stores a halved value
for later use. Then, treating the bits representing the floating-point number as a 32-bit
integer, a logical shift right by one bit is performed and the result subtracted from the
magic number 0x5F3759DF. This is the first approximation of the inverse square root of the
input. Treating the bits again as a floating-point number, it runs one iteration of Newton’s
approximation method, yielding a more precise approximation.
Let’s say there is a number in exponent form or scientific notation:
=100 million
Now, to find the regular square root, we’d just divide the exponent by 2:
And if, want to know the inverse square root, divide the exponent by -2 to flip the sign:
So, the code converts the floating-point number into an integer. It then shifts the bits by
one, which means the exponent bits are divided by 2 (when we eventually turn the bits
back into a float). And lastly, to negate the exponent, we subtract from the magic number
0x5f3759df. This does a few things: it preserves the mantissa (the non-exponent part, aka
5 in: 5 · ), handles odd-even exponents, shifting bits from the exponent into the
mantissa, and all sorts of funky stuff.
The following code is the fast inverse square root implementation from Quake III Arena (ex-
act original comment written in Quake III Arena Game).
859
Chapter 139. Fast inverse square root
Output :
0.0623942
Source
https://www.geeksforgeeks.org/fast-inverse-square-root/
860
Chapter 140
Examples :
Input : 10
Output : YES
Explanation: 1010 is the binary representation
of 10 which does not contains any
consecutive 1's.
Input : 11
Output : NO
Explanation: 1011 is the binary representation
of 11, which contains consecutive
1's
The idea to do this is to right shift the number, till n!=0. For every binary representation
of 1, check if the last bit found was 1 or not. Get the last bit of binary representation of the
integer by doing a (n&1). If the last bit of the binary representation is 1 and the previous
bit before doing a right shift was also one, we encounter consecutive 1’s. So we come to the
conclusion that it is not a fibonnary number.
Some of the first few Fibonnary numbers are:
861
Chapter 140. Fibbinary Numbers (No consecutive 1s in binary)
CPP
Java
862
Chapter 140. Fibbinary Numbers (No consecutive 1s in binary)
Python3
863
Chapter 140. Fibbinary Numbers (No consecutive 1s in binary)
C#
864
Chapter 140. Fibbinary Numbers (No consecutive 1s in binary)
PHP
<?php
// PHP program to check if a number
// is fibinnary number or not
865
Chapter 140. Fibbinary Numbers (No consecutive 1s in binary)
Output :
YES
Source
https://www.geeksforgeeks.org/httpswww-geeksforgeeks-orgfibbinary-numbers/
866
Chapter 141
Input : 10
Output : Yes
Explanation: 1010 is the binary representation
of 10 which does not contains any
consecutive 1's.
Input : 11
Output : No
Explanation: 1011 is the binary representation
of 11, which contains consecutive
1's.
Approach: If (n & (n >> 1)) == 0, then ‘n’ is a fibbinary number Else not.
C++
867
Chapter 141. Fibbinary Numbers (No consecutive 1s in binary) – O(1) Approach
#include <bits/stdc++.h>
using namespace std;
// function to check whether a number
// is fibbinary or not
bool isFibbinaryNum(unsigned int n) {
// if the number does not contain adjacent ones
// then (n & (n >> 1)) operation results to 0
if ((n & (n >> 1)) == 0)
return true;
// not a fibbinary number
return false;
}
// Driver program to test above
int main() {
unsigned int n = 10;
if (isFibbinaryNum(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
868
Chapter 141. Fibbinary Numbers (No consecutive 1s in binary) – O(1) Approach
int n = 10;
if (isFibbinaryNum(n) == true)
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
C#
869
Chapter 141. Fibbinary Numbers (No consecutive 1s in binary) – O(1) Approach
class GFG {
// function to check whether a number
// is fibbinary or not
static bool isFibbinaryNum(int n) {
// if the number does not contain
// adjacent ones then (n & (n >> 1))
// operation results to 0
if ((n & (n >> 1)) == 0)
return true;
// not a fibbinary number
return false;
}
// Driver program to test above
public static void Main() {
int n = 10;
if (isFibbinaryNum(n) == true)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP implementation to check whether
// a number is fibbinary or not
// function to check whether a number
// is fibbinary or not
function isFibbinaryNum($n)
{
// if the number does not contain
// adjacent ones then (n & (n >> 1))
// operation results to 0
if (($n & ($n >> 1)) == 0)
return true;
// not a fibbinary number
870
Chapter 141. Fibbinary Numbers (No consecutive 1s in binary) – O(1) Approach
return false;
}
// Driver code
$n = 10;
if (isFibbinaryNum($n))
echo "Yes";
else
echo "No";
// This code is contributed by mits
?>
Output :
Yes
Source
https://www.geeksforgeeks.org/fibbinary-numbers-no-consecutive-1s-binary-o1-approach/
871
Chapter 142
872
Chapter 142. Find Duplicates of array using bit array
873
Chapter 142. Find Duplicates of array using bit array
{
// create a bit with 32000 bits
BitArray ba = new BitArray(320000);
// Traverse array elements
for (int i=0; i<arr.length; i++)
{
// Index in bit array
int num = arr[i] - 1;
// If num is already present in bit array
if (ba.get(num))
System.out.print(num +" ");
// Else insert num
else
ba.set(num);
}
}
// Driver code
public static void main(String[] args) throws
java.lang.Exception
{
int[] arr = {1, 5, 1, 10, 12, 10};
checkDuplicates(arr);
}
}
Output:
1 10
Source
https://www.geeksforgeeks.org/find-duplicates-of-array-using-bit-array/
874
Chapter 143
Input: x = 6
Output: Next Sparse Number is 8
Input: x = 4
Output: Next Sparse Number is 4
Input: x = 38
Output: Next Sparse Number is 40
Input: x = 44
Output: Next Sparse Number is 64
875
Chapter 143. Find Next Sparse Number
else
x++
}
Time complexity of isSparse() is O(Log x). Time complexity of this solution is O(x Log x).
The next sparse number can be at most O(x) distance away.
Thanks to kk_angel for suggesting above solution.
An Efficient Solution can solve this problem without checking all numbers on by one.
Below are steps.
876
Chapter 143. Find Next Sparse Number
Output:
877
Chapter 143. Find Next Sparse Number
Source
https://www.geeksforgeeks.org/given-a-number-find-next-sparse-number/
878
Chapter 144
Input : n = 5
Output : 2
Input : n = 255
Output : 0
Input : n = 26
Output : 5
879
Chapter 144. Find One’s Complement of an Integer
// XOR the given integer with poe(2,
// number_of_bits-1 and print the result
return ((1 << number_of_bits) - 1) ^ n;
}
int main()
{
unsigned int n = 22;
cout << onesComplement(n);
return 0;
}
Java
Python3
880
Chapter 144. Find One’s Complement of an Integer
import math
def onesComplement(n):
# Find number of bits in
# the given integer
number_of_bits = (int)(math.floor(math.log(n) /
math.log(2))) + 1;
# XOR the given integer with poe(2,
# number_of_bits-1 and print the result
return ((1 << number_of_bits) - 1) ^ n;
# Driver code
n = 22
print(onesComplement(n))
# This code is contributed by Anant Agarwal.
C#
881
Chapter 144. Find One’s Complement of an Integer
Output :
Source
https://www.geeksforgeeks.org/find-ones-complement-integer/
882
Chapter 145
Find Two Missing Numbers | Set 1 (An Interesting Linear Time Solution)
We have discussed two methods to solve this problem in above article. The method 1 requires
O(n) extra space and method 2 can causes overflow. In this post, a new solution is discussed.
The solution discussed here is O(n) time, O(1) extra space and causes no overflow.
Below are steps.
1. Find XOR of all array elements and natural numbers from 1 to n. Let the array be
arr[] = {1, 3, 5, 6}
XOR = (1 ^ 3 ^ 5 ^ 6) ^ (1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6)
883
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
2. As per the property of XOR, same elements will cancel out and we will be left with 2
XOR 4 = 6 (110). But we don’t know the exact numbers,let them be X and Y.
3. A bit is set in xor only if corresponding bits in X and Y are different. This is the
crucial step to understand.
4. We take a set bit in XOR. Let us consider the rightmost set bit in XOR, set_bit_no
= 010
5. Now again if we XOR all the elements of arr[] and 1 to n that have rightmost bit set
we will get one of the repeating numbers, say x.
6. Similarly, if we XOR all the elements of arr[] and 1 to n that have rightmost bit not
set, we will get the other element, say y.
C++
884
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
Java
885
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
886
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
System.out.println("Two Missing Numbers are ");
System.out.println( x + " " + y);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {1, 3, 5, 6};
// Range of numbers is 2 plus size of array
int n = 2 +arr.length;
findTwoMissingNumbers(arr, n);
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
887
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
# Get a set bit of XOR
# (We get the rightmost set bit)
set_bit_no = XOR & ~(XOR-1)
# Now divide elements in two sets
# by comparing rightmost
# set bit of XOR with bit at same
# position in each element.
x = 0
# Initialize missing numbers
y = 0
for i in range(0,n-2):
if arr[i] & set_bit_no:
# XOR of first set in arr[]
x = x ^ arr[i]
else:
# XOR of second set in arr[]
y = y ^ arr[i]
for i in range(1,n+1):
if i & set_bit_no:
# XOR of first set in arr[] and
# {1, 2, ...n }
x = x ^ i
else:
# XOR of second set in arr[] and
# {1, 2, ...n }
y = y ^ i
print ("Two Missing Numbers are\n%d %d"%(x,y))
# Driver program to test
# above function
arr = [1, 3, 5, 6]
# Range of numbers is 2
# plus size of array
n = 2 + len(arr)
findTwoMissingNumbers(arr, n)
# This code is contributed
888
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
# by Shreyanshi Arun.
C#
889
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
else
// XOR of second set in arr[]
y = y ^ arr[i];
}
for (int i = 1; i <= n; i++) {
if ((i & set_bit_no) > 0)
// XOR of first set in arr[]
// and {1, 2, ...n }
x = x ^ i;
else
// XOR of second set in arr[]
// and {1, 2, ...n }
y = y ^ i;
}
Console.WriteLine("Two Missing Numbers are ");
Console.WriteLine(x + " " + y);
}
// Driver program
public static void Main()
{
int[] arr = { 1, 3, 5, 6 };
// Range of numbers is 2 plus
// size of array
int n = 2 + arr.Length;
findTwoMissingNumbers(arr, n);
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP Program to find 2 Missing
// Numbers using O(1) extra
// space and no overflow.
// Function to find two
// missing numbers in range
// [1, n]. This function
// assumes that size of array
// is n-2 and all array
890
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
891
Chapter 145. Find Two Missing Numbers | Set 2 (XOR based solution)
// XOR of first set in arr[]
// and {1, 2, ...n }
$x = $x ^ $i;
else
// XOR of second set in arr[]
// and {1, 2, ...n }
$y = $y ^ $i;
}
echo "Two Missing Numbers are\n", $x;
echo "\n", $y;
}
// Driver Code
$arr = array(1, 3, 5, 6);
// Range of numbers is 2
// plus size of array
$n = 2 + count($arr);
findTwoMissingNumbers($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/find-two-missing-numbers-set-2-xor-based-solution/
892
Chapter 146
Input : 6, 1, 3, 5, 1, 3, 7, 6
Output : 5 7
All elements appear twice except 5 and 7
Input : 1 3 4 1
Output : 3 4
C++
893
Chapter 146. Find Unique pair in an array with pairs of numbers
// of pairs.
#include <stdio.h>
void findUniquePair(int arr[], int n)
{
// XOR each element and get XOR of two unique
// elements(ans)
int XOR = arr[0];
for (int i = 1; i < n; i++)
XOR = XOR ^ arr[i];
// Now XOR has XOR of two missing elements. Any set
// bit in it must be set in one missing and unset in
// other missing number
// Get a set bit of XOR (We get the rightmost set bit)
int set_bit_no = XOR & ~(XOR-1);
// Now divide elements in two sets by comparing rightmost
// set bit of XOR with bit at same position in each element.
int x = 0, y = 0; // Initialize missing numbers
for (int i = 0; i < n; i++)
{
if (arr[i] & set_bit_no)
x = x ^ arr[i]; /*XOR of first set in arr[] */
else
y = y ^ arr[i]; /*XOR of second set in arr[] */
}
printf("The unique pair is (%d, %d)", x, y);
}
// Driver code
int main()
{
int a[] = { 6, 1, 3, 5, 1, 3, 7, 6 };
int n = sizeof(a)/sizeof(a[0]);
findUniquePair(a, n);
return 0;
}
Java
894
Chapter 146. Find Unique pair in an array with pairs of numbers
895
Chapter 146. Find Unique pair in an array with pairs of numbers
Python 3
896
Chapter 146. Find Unique pair in an array with pairs of numbers
n = len(a)
findUniquePair(a, n)
# This code is contributed by Smitha.
C#
897
Chapter 146. Find Unique pair in an array with pairs of numbers
}
Console.WriteLine("The unique pair is ("
+ x + ", " + y + ")");
}
// Driver code
public static void Main ()
{
int[] a = { 6, 1, 3, 5, 1, 3, 7, 6 };
int n = a.Length;
findUniquePair(a, n);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find a
// unique pair in an array
// of pairs.
function findUniquePair($arr, $n)
{
// XOR each element and
// get XOR of two unique
// elements(ans)
$XOR = $arr[0];
for ($i = 1; $i < $n; $i++)
$XOR = $XOR ^ $arr[$i];
// Now XOR has XOR of two
// missing elements. Any set
// bit in it must be set in
// one missing and unset in
// other missing number
// Get a set bit of XOR
// (We get the rightmost set bit)
$set_bit_no = $XOR & ~($XOR-1);
// Now divide elements in two
// sets by comparing rightmost
// set bit of XOR with bit at
898
Chapter 146. Find Unique pair in an array with pairs of numbers
Output:
Source
https://www.geeksforgeeks.org/find-unique-pair-array-pairs-numbers/
899
Chapter 147
Input: x = 1, y = 2
Output: 3
Input: x = 3, y = 5
Output: 6
A Simple Solution is to traverse all bits one by one. For every pair of bits, check if both
are same, set the corresponding bit as 0 in output, otherwise set as 1.
C++
900
Chapter 147. Find XOR of two number without using XOR operator
{
// Find current bits in x and y
bool b1 = x & (1 << i);
bool b2 = y & (1 << i);
// If both are 1 then 0 else xor is same as OR
bool xoredBit = (b1 & b2) ? 0 : (b1 | b2);
// Update result
res <<= 1;
res |= xoredBit;
}
return res;
}
// Driver program to test above function
int main()
{
int x = 3, y = 5;
cout << "XOR is " << myXOR(x, y);
return 0;
}
Output :
XOR is 6
901
Chapter 147. Find XOR of two number without using XOR operator
{
return (x | y) & (~x | ~y);
}
// Driver program to test above function
int main()
{
int x = 3, y = 5;
cout << "XOR is " << myXOR(x, y);
return 0;
}
Java
Python 3
902
Chapter 147. Find XOR of two number without using XOR operator
(~x | ~y))
# Driver Code
x = 3
y = 5
print("XOR is" ,
myXOR(x, y))
# This code is contributed
# by Smitha
C#
// C# program to find
// XOR without using ^
using System;
class GFG
{
// Returns XOR of x and y
static int myXOR(int x, int y)
{
return (x | y) &
(~x | ~y);
}
// Driver Code
static public void Main ()
{
int x = 3, y = 5;
Console.WriteLine("XOR is "+
(myXOR(x, y)));
}
}
// This code is contibuted by m_kit
PHP
<?php
// PHP program to find
// XOR without using ^
// Returns XOR of x and y
function myXOR($x, $y)
{
903
Chapter 147. Find XOR of two number without using XOR operator
Output :
XOR is 6
Source
https://www.geeksforgeeks.org/find-xor-of-two-number-without-using-xor-operator/
904
Chapter 148
Examples :
Input: [9, 12, 23, 10, 12, 12, 15, 23, 14, 12, 15]
Output: 12, 23 and 15
Input: [1, 4, 7, 5, 9, 7, 3, 4, 6, 8, 3, 0, 3]
Output: 4 and 7
A simple method would be to traverse the array and store frequencies of its elements in a
map. Later, print elements that have even count in the map. The solution takes O(n) time
but requires extra space for storing frequencies. Below is an interesting method to solve this
problem using bitwise operators.
This method assumes that long long integers are stored using 64 bits. The idea is to use
XOR operator. We know that
1 XOR 1 = 0
905
Chapter 148. Find even occurring elements in an array of limited range
1 XOR 0 = 1
0 XOR 1 = 1
0 XOR 0 = 0
1, 4, 7, 5, 9, 7, 3, 4, 6, 8, 3, 0, 3
If we right shift 1 by value of each element of the array and take XOR of all the items, we
will get below binary integer –
1101101011
Each 1 in the i’th index from the right represents odd occurrence of element i. And each 0
in the i’th index from the right represents even or non-occurrence of element i in the array.
0 is present in 2nd, 4th and 7th position in above binary number. But 2 is not present in
our array. So our answer is 4 and 7.
Below is C++ implementation of above idea
C++
906
Chapter 148. Find even occurring elements in an array of limited range
{
// right shift 1 by value of current element
pos = 1 << arr[i];
// Each 0 in _xor represents an even occurrence
if (!(pos & _xor))
{
// print the even occurring numbers
cout << arr[i] << " ";
// set bit as 1 to avoid printing duplicates
_xor ^= pos;
}
}
}
// Driver code
int main()
{
int arr[] = { 9, 12, 23, 10, 12, 12, 15, 23,
14, 12, 15 };
int n = sizeof(arr) / sizeof(arr[0]);
printRepeatingEven(arr, n);
return 0;
}
PHP
<?php
// PHP Program to find the even
// occurring elements in given array
// Function to find the even
// occurring elements in given array
function printRepeatingEven($arr, $n)
{
$_xor = 0;
$pos;
// do for each element of array
for( $i = 0; $i < $n; ++$i)
{
// right pos 1 by value
// of current element
$pos = 1 << $arr[$i];
907
Chapter 148. Find even occurring elements in an array of limited range
Output :
12 23 15
Improved By : jit_t
Source
https://www.geeksforgeeks.org/find-even-occurring-elements-array-limited-range/
908
Chapter 149
Find i’th index character in a binary string obtained after n iterations | Set 2 - GeeksforGeeks
Given a decimal number m, convert it into a binary string and apply n iterations, in each
iteration 0 becomes “01” and 1 becomes “10”. Find ith(based indexing) index character in
the string after nth iteration.
Examples:
Input: m = 5 i = 5 n = 3
Output: 1
Explanation
In the first case m = 5, i = 5, n = 3.
Initially, the string is 101 ( binary equivalent of 5 )
After 1st iteration - 100110
After 2nd iteration - 100101101001
After 3rd iteration - 100101100110100110010110
The character at index 5 is 1, so 1 is the answer
Input: m = 11 i = 6 n = 4
Output: 1
A naive approach to this problem has been discussed in the previous post.
Efficient algorithm: The first step will be to find which block the i-th character will be
after N iterations are performed. In the n’th iteration distance between any two consecutive
characters initially will always be equal to 2^n. For a general number m, the number of
blocks will be ceil(log m). If M was 3, the string gets divided into 3 blocks. Find the block
number in which kth character will lie by k / (2^n), where n is the number of iterations.
909
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
Consider m=5, then the binary representation is 101. Then the distance between any 2
consecutive marked characters in any i’th iteration will be as follows
0th iteration: 101, distance = 0
1st iteration: 10 01 1 0, distance = 2
2nd iteration: 1001 0110 1001, distance = 4
3rd iteration: 10010110 01101001 10010110, distance = 8
In the example k = 5 and n = 3, so Block_number, when k is 5, will be 0, as 5 / (2^3) = 0
Initially, block numbers will be
Original String : 1 0 1
Block_number : 0 1 2
There is no need to generate the entire string, only computing in the block in which
the i-th character is present will give the answer. Let this character be root root =
s[Block_number], where s is the binary representation of “m”. Now in the final string,
find the distance of the kth character from the block number, call this distance as remaining.
So remaining = k % (2^n) will be the index of i-th character in the block. If remaining is
0, the root will be the answer. Now, in order to check whether the root is the actual answer
use a boolean variable flip which whether we need to flip our answer or not. Following the
below algorithm will give the character at the i-th index.
910
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
C++
911
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
int s[32], x = 0;
// binary representation of M
for (; m > 0; x++) {
s[x] = m % 2;
m = m / 2;
}
// kth digit will be derived from root for sure
int root = s[x - 1 - Block_number];
if (remaining == 0) {
cout << root << endl;
return;
}
// Check whether there is need to
// flip root or not
bool flip = true;
while (remaining > 1) {
if (remaining & 1) {
flip = !flip;
}
remaining = remaining >> 1;
}
if (flip) {
cout << !root << endl;
}
else {
cout << root << endl;
}
}
// Driver Code
int main()
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
return 0;
}
Java
912
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
import java.io.*;
class GFG
{
// Function to find
// the i-th character
static void KthCharacter(int m,
int n, int k)
{
// distance between two
// consecutive elements
// after N iterations
int distance = (int)Math.pow(2, n);
int Block_number = k / distance;
int remaining = k % distance;
int s[] = new int[32];
int x = 0;
// binary representation of M
for (; m > 0; x++)
{
s[x] = m % 2;
m = m / 2;
}
// kth digit will be
// derived from root
// for sure
int root = s[x - 1 -
Block_number];
if (remaining == 0)
{
System.out.println(root);
return;
}
// Check whether there is
// need to flip root or not
Boolean flip = true;
while (remaining > 1)
{
if ((remaining & 1) > 0)
{
flip = !flip;
}
remaining = remaining >> 1;
913
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
}
if (flip)
{
System.out.println(!(root > 0));
}
else
{
System.out.println(root);
}
}
// Driver Code
public static void main (String[] args)
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
}
}
// This code is contributed
// by anuj_67.
Python3
914
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
x += 1
# kth digit will be derived
# from root for sure
root = s[x - 1 - Block_number]
if (remaining == 0):
print(root)
return
# Check whether there
# is need to flip root
# or not
flip = True
while (remaining > 1):
if (remaining & 1):
flip = not(flip)
remaining = remaining >> 1
if (flip) :
print(not(root))
else :
print(root)
# Driver Code
m = 5
k = 5
n = 3
KthCharacter(m, n, k)
# This code is contributed
# by smita
C#
915
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
int n,
int k)
{
// distance between two
// consecutive elements
// after N iterations
int distance = (int)Math.Pow(2, n);
int Block_number = k / distance;
int remaining = k % distance;
int []s = new int[32];
int x = 0;
// binary representation of M
for (; m > 0; x++)
{
s[x] = m % 2;
m = m / 2;
}
// kth digit will be
// derived from root
// for sure
int root = s[x - 1 -
Block_number];
if (remaining == 0)
{
Console.WriteLine(root);
return;
}
// Check whether there is
// need to flip root or not
Boolean flip = true;
while (remaining > 1)
{
if ((remaining & 1) > 0)
{
flip = !flip;
}
remaining = remaining >> 1;
}
if (flip)
{
Console.WriteLine(!(root > 0));
916
Chapter 149. Find i’th index character in a binary string obtained after n iterations | Set 2
}
else
{
Console.WriteLine(root);
}
}
// Driver Code
public static void Main ()
{
int m = 5, k = 5, n = 3;
KthCharacter(m, n, k);
}
}
// This code is contributed
// by anuj_67.
Output:
Time Complexity: O(log Z), where Z is the distance between initially consecutive bits
after N iterations
Improved By : vt_m, Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/find-ith-index-character-in-a-binary-string-obtained-after-n-iterations-set-2/
917
Chapter 150
Find largest element from array without using conditional operator - GeeksforGeeks
Given an array of n-elements, we have to find the largest element among them without using
any conditional operator like greater than or less than.
Examples:
First Approach (Use of Hashing) : To find the largest element from the array we may
use the concept the of hashing where we should maintain a hash table of all element and
then after processing all array element we should find the largest element in hash by simply
traversing the hash table from end.
But there are some drawbacks of this approach like in case of very large elements maintaining
a hash table is either not possible or not feasible.
Better Approach (Use of Bitwise AND) : Recently we have learn how to find the
largest AND value pair from a given array. Also, we know that if we take bitwise AND
of any number with INT_MAX (whose all bits are set bits) then the result will be that
number itself. Now, using this property we will try to find the largest element from the
array without any use conditional operator like greater than or less than.
For finding the largest element we will first insert an extra element i.e. INT_MAX in array,
and after that we will try to find the maximum AND value of any pair from the array.
918
Chapter 150. Find largest element from array without using conditional operator
This obtained maximum value will contain AND value of INT_MAX and largest element
of original array and is our required result.
Below is the implementation of above approach :
CPP
919
Chapter 150. Find largest element from array without using conditional operator
// Driver function
int main()
{
int arr[] = { 4, 8, 6, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Largest element = " << largest(arr, n);
return 0;
}
PHP
<?php
// php Program to find largest
// element from array
// Utility function to check
// number of elements having
// set msb as of pattern
function checkBit($pattern,$arr,$n)
{
$count = 0;
for ($i = 0; $i < $n; $i++)
if (($pattern & $arr[$i]) == $pattern)
$count++;
return $count;
}
// Function for finding
// maximum and value pair
function largest($arr, $n)
{
$res = 0;
// Iterate over total of
// 30bits from msb to lsb
for ($bit = 31; $bit >= 0; $bit--)
{
// Find the count of element
// having set msb
$count = checkBit($res | (1 << $bit),$arr, $n);
// if count | 1 != 1 set
// particular bit in result
if ($count | 1 != 1)
$res |= (1 << $bit);
}
920
Chapter 150. Find largest element from array without using conditional operator
return $res;
}
// Driver code
$arr = array( 4, 8, 6, 2 );
$n = sizeof($arr) / sizeof($arr[0]);
echo "Largest element = ". largest($arr, $n);
// This code is contributed by mits
?>
Output:
Largest element = 8
Source
https://www.geeksforgeeks.org/find-largest-element-array-without-using-conditional-operator/
921
Chapter 151
Find longest sequence of 1’s in binary representation with one flip - GeeksforGeeks
Give an integer n. We can flip exactly one bit. Write code to find the length of the longest
sequence of 1 s you could create.
Examples:
Input : 1775
Output : 8
Binary representation of 1775 is 11011101111.
After flipping the highlighted bit, we get
consecutive 8 bits. 11011111111.
Input : 12
Output : 3
Input : 15
Output : 5
Input : 71
Output: 4
922
Chapter 151. Find longest sequence of 1’s in binary representation with one flip
923
Chapter 151. Find longest sequence of 1’s in binary representation with one flip
Python3
924
Chapter 151. Find longest sequence of 1’s in binary representation with one flip
currLen = 0;
prevLen = 0;
maxLen = 0;
while (a > 0):
# If Current bit is a 1
# then increament currLen++
if ((a & 1) == 1):
currLen += 1;
# If Current bit is a 0
# then check next bit of a
elif ((a & 1) == 0):
# Update prevLen to 0
# (if next bit is 0)
# or currLen (if next
# bit is 1). */
prevLen = 0 if((a & 2) == 0) else currLen;
# If two consecutively bits
# are 0 then currLen also
# will be 0.
currLen = 0;
# Update maxLen if required
maxLen = max(prevLen + currLen, maxLen);
# Remove last bit (Right shift)
a >>= 1;
# We can always have a sequence
# of at least one 1, this is
# fliped bit
return maxLen + 1;
# Driver code
# input 1
print(flipBit(13));
# input 2
print(flipBit(1775));
# input 3
print(flipBit(15));
# This code is contributed by mits
925
Chapter 151. Find longest sequence of 1’s in binary representation with one flip
PHP
<?php
// PHP program to find maximum consecutive
// 1's in binary representation of a number
// after flipping one bit.
function flipBit($a)
{
/* If all bits are l,
binary representation
of 'a' has all 1s */
if (~$a == 0)
return 8 * sizeof();
$currLen = 0;
$prevLen = 0;
$maxLen = 0;
while ($a!= 0)
{
// If Current bit is a 1
// then increament currLen++
if (($a & 1) == 1)
$currLen++;
// If Current bit is a 0
// then check next bit of a
else if (($a & 1) == 0)
{
/* Update prevLen to 0
(if next bit is 0)
or currLen (if next
bit is 1). */
$prevLen = ($a & 2) == 0? 0 : $currLen;
// If two consecutively bits are 0
// then currLen also will be 0.
$currLen = 0;
}
// Update maxLen if required
$maxLen = max($prevLen + $currLen, $maxLen);
// Remove last bit (Right shift)
$a >>= 1;
}
926
Chapter 151. Find longest sequence of 1’s in binary representation with one flip
// We can always have a sequence of
// at least one 1, this is fliped bit
return $maxLen+1;
}
// Driver code
// input 1
echo flipBit(13);
echo "\n";
// input 2
echo flipBit(1775);
echo "\n";
// input 3
echo flipBit(15);
// This code is contributed by aj_36
?>
Output :
4
8
5
Source
https://www.geeksforgeeks.org/find-longest-sequence-1s-binary-representation-one-flip/
927
Chapter 152
A simple solution is to one by one consider every element of first array and search in
second array. As soon as we find a missing element, we return. Time complexity of this
solution is O(n2 )
An efficient solution is based on XOR. The combined occurrence of each element is twice,
one in ‘arr1’ and other in ‘arr2’, except one element which only has a single occurrence in
‘arr1’. We know that (a Xor a) = 0. So, simply XOR the elements of both the arrays. The
result will be the missing number.
C++
928
Chapter 152. Find missing number in another array which is shuffled copy
Java
929
Chapter 152. Find missing number in another array which is shuffled copy
{
// Missing number 'mnum'
int mnum = 0;
// 1st array is of size 'n'
for (int i = 0; i < n; i++)
mnum = mnum ^ arr1[i];
// 2nd array is of size 'n - 1'
for (int i = 0; i < n - 1; i++)
mnum = mnum ^ arr2[i];
// Required missing number
return mnum;
}
// Driver Code
public static void main (String[] args)
{
int arr1[] = {4, 8, 1, 3, 7};
int arr2[] = {7, 4, 3, 1};
int n = arr1.length;
System.out.println("Missing number = "
+ missingNumber(arr1, arr2, n));
}
}
Python3
930
Chapter 152. Find missing number in another array which is shuffled copy
C#
931
Chapter 152. Find missing number in another array which is shuffled copy
PHP
<?php
// PHP implementation to find the
// missing number in shuffled array
// PHP implementation to find the
// missing number in shuffled array
// Returns the missing number
// Size of arr2[] is n-1
function missingNumber($arr1, $arr2,
$n)
{
// Missing number 'mnum'
$mnum = 0;
// 1st array is of size 'n'
for ($i = 0; $i < $n; $i++)
$mnum = $mnum ^ $arr1[$i];
// 2nd array is of size 'n - 1'
for ($i = 0; $i < $n - 1; $i++)
$mnum = $mnum ^ $arr2[$i];
// Required missing number
return $mnum;
}
// Driver Code
$arr1 = array(4, 8, 1, 3, 7);
$arr2 = array(7, 4, 3, 1);
$n = count($arr1);
echo "Missing number = "
, missingNumber($arr1, $arr2, $n);
// This code is contributed by anuj_67.
?>
Output:
932
Chapter 152. Find missing number in another array which is shuffled copy
Missing number = 8
Source
https://www.geeksforgeeks.org/find-missing-number-another-array-shuffled-copy/
933
Chapter 153
Input : 10
Output : 8
Binary representation of 10 is 1010
The most significant bit corresponds
to decimal number 8.
Input : 18
Output : 16
A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count
while doing this. This count actually represents position of MSB.
C++
934
Chapter 153. Find most significant set bit of a number
return 0;
int msb = 0;
while (n != 0) {
n = n / 2;
msb++;
}
return (1 << msb);
}
// Driver code
int main()
{
int n = 0;
cout << setBitNumber(n);
return 0;
}
Java
935
Chapter 153. Find most significant set bit of a number
}
// This code is contributed by ajit
Python3
C#
936
Chapter 153. Find most significant set bit of a number
PHP
<?php
// Simple PhP program
// to find MSB number
// for given n.
function setBitNumber($n)
{
if ($n == 0)
return 0;
$msb = 0;
while ($n != 0)
{
$n = $n / 2;
$msb++;
}
return (1 << $msb);
}
// Driver code
$n = 0;
echo setBitNumber($n);
// This code is contributed
// by akt_mit
?>
Output:
937
Chapter 153. Find most significant set bit of a number
An efficient solution for a fixed size integer (say 32 bits) is to one by one set bits, then
add 1 so that only the bit after MSB is set. Finally right shift by 1 and return answer. This
solution does not require any condition checking.
C++
938
Chapter 153. Find most significant set bit of a number
Java
939
Chapter 153. Find most significant set bit of a number
Python3
C#
940
Chapter 153. Find most significant set bit of a number
class GFG {
static int setBitNumber(int n)
{
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// Increment n by 1 so that
// there is only one set bit
// which is just before original
// MSB. n now becomes 1000000000
n = n + 1;
// Return original MSB after shifting.
// n now becomes 100000000
return (n >> 1);
}
// Driver code
public static void Main()
{
int n = 273;
Console.WriteLine(setBitNumber(n));
}
}
// This code is contributed by Sam007.
PHP
<?php
941
Chapter 153. Find most significant set bit of a number
Output:
942
Chapter 153. Find most significant set bit of a number
256
C++
Java
943
Chapter 153. Find most significant set bit of a number
// To find the position of the
// most significant set bit
int k = (int)(Math.log(n) / Math.log(2));
// To return the the value of the number
// with set bit at k-th position
return (int)(Math.pow(2, k));
}
// Driver code
public static void main(String arg[])
{
int n = 273;
System.out.print(setBitNumber(n));
}
}
Python3
C#
944
Chapter 153. Find most significant set bit of a number
static int setBitNumber(int n)
{
// To find the position of the
// most significant set bit
int k = (int)(Math.Log(n) / Math.Log(2));
// To return the the value of the number
// with set bit at k-th position
return (int)(Math.Pow(2, k));
}
// Driver code
static public void Main()
{
int n = 273;
Console.WriteLine(setBitNumber(n));
}
}
PHP
<?php
// PHP program to find MSB
// number for given n.
function setBitNumber($n)
{
// To find the position
// of the most significant
// set bit
$k =(int)(log($n,2));
// To return the the value
// of the number with set
// bit at k-th position
return (int)(pow(2, $k));
}
// Driver code
$n = 273;
echo setBitNumber($n);
// This code is contributed
// by jit_t.
?>
945
Chapter 153. Find most significant set bit of a number
Output:
256
Source
https://www.geeksforgeeks.org/find-significant-set-bit-number/
946
Chapter 154
Input: n = 2
Output: 25
Input: n = 5
Output: 130
If we notice carefully the magic numbers can be represented as 001, 010, 011, 100, 101,
110 etc, where 001 is 0*pow(5,3) + 0*pow(5,2) + 1*pow(5,1). So basically we need to add
powers of 5 for each bit set in given integer n.
Below is the implementation based on this idea.
C++
947
Chapter 154. Find nth Magic Number
Java
948
Chapter 154. Find nth Magic Number
}
return answer;
}
// Driver program to test
// above function
public static void main(String[] args)
{
int n = 5;
System.out.println("nth magic" +
" number is " + nthMagicNo(n));
}
}
// This code is contributed by
// prerna saini
Python3
949
Chapter 154. Find nth Magic Number
C#
PHP
<?php
950
Chapter 154. Find nth Magic Number
Output :
951
Chapter 154. Find nth Magic Number
Source
https://www.geeksforgeeks.org/find-nth-magic-number/
952
Chapter 155
Given an array of size N. Find the number of pairs (i, j) such that XOR =
0, and 1 <= i < j <= N.
Examples :
to the answer.
953
Chapter 155. Find number of pairs in an array such that their XOR is 0
954
Chapter 155. Find number of pairs in an array such that their XOR is 0
Java
955
Chapter 155. Find number of pairs in an array such that their XOR is 0
Python3
956
Chapter 155. Find number of pairs in an array such that their XOR is 0
C#
957
Chapter 155. Find number of pairs in an array such that their XOR is 0
PHP
<?php
// PHP program to find number
// of pairs in an array such
// that their XOR is 0
// Function to calculate
// the count
function calculate($a, $n)
{
// Sorting the list using
// built in function
sort($a);
$count = 1;
$answer = 0;
// Traversing through the
// elements
for ($i = 1; $i < $n; $i++)
{
958
Chapter 155. Find number of pairs in an array such that their XOR is 0
Output :
959
Chapter 155. Find number of pairs in an array such that their XOR is 0
C++
Python 3
960
Chapter 155. Find number of pairs in an array such that their XOR is 0
PHP
Output :
961
Chapter 155. Find number of pairs in an array such that their XOR is 0
Source
https://www.geeksforgeeks.org/find-number-pairs-array-xor-0/
962
Chapter 156
963
Chapter 156. Find one extra character in a string
Output:
Method 3(Bits):-
traverse first and second string from starting with xor operation at the end you get the
character which is extra.
Time Complexity:- O(n+n+1)
Space Complexity:- O(1).
C++
964
Chapter 156. Find one extra character in a string
Java
965
Chapter 156. Find one extra character in a string
String strB)
{
// result store the result
int res = 0, i;
// traverse string A till
// end and xor with res
for (i = 0; i < strA.length(); i++)
{
// xor with res
res ^= strA.charAt(i);
}
// traverse string B till end and
// xor with res
for (i = 0; i < strB.length(); i++)
{
// xor with res
res ^= strB.charAt(i);
}
// print result at the end
return ((char)(res));
}
// Driver code
public static void main(String args[])
{
// given string
String strA = "abcd";
String strB = "cbdad";
System.out.println(findExtraCharcter(strA, strB));
}
}
/*This code is contributed by Nikita Tiwari.*/
Python 3
966
Chapter 156. Find one extra character in a string
C#
967
Chapter 156. Find one extra character in a string
// xor with res
res ^= strB[i];
}
// print result at the end
return ((char)(res));
}
// Driver Code
public static void Main()
{
// given string
string strA = "abcd";
string strB = "cbdad";
Console.WriteLine(
findExtraCharcter(strA, strB));
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP program to find extra character in
// one string
function findExtraCharcter($strA, $strB)
{
// result store the result
$res = 0;
// traverse string A till end and
// xor with res
for ($i = 0; $i < strlen($strA); $i++)
{
// xor with res
$res ^= ord($strA[$i]);
}
// traverse string B till end and
// xor with res
for ($i = 0; $i < strlen($strB); $i++)
{
968
Chapter 156. Find one extra character in a string
Output:
Source
https://www.geeksforgeeks.org/find-one-extra-character-string/
969
Chapter 157
970
Chapter 157. Find position of the only set bit
PHP
<?php
// PHP program to find position of
// only set bit in a given number
// A utility function to check
// whether n is power of 2 or
// not. See http://goo.gl/17Arj
function isPowerOfTwo($n)
{
return $n && (!($n & ($n - 1)));
971
Chapter 157. Find position of the only set bit
}
// Returns position of the
// only set bit in 'n'
function findPosition($n)
{
if (!isPowerOfTwo($n))
return -1;
$i = 1;
$pos = 1;
// Iterate through bits of n
// till we find a set bit i&n
// will be non-zero only when
// 'i' and 'n' have a set bit
// at same position
while (!($i & $n))
{
// Unset current bit and
// set the next bit in 'i'
$i = $i << 1;
// increment position
++$pos;
}
return $pos;
}
// Driver Code
$n = 16;
$pos = findPosition($n);
if (($pos == -1) == true)
echo "n =", $n, "," ,
" Invalid number" , "\n";
else
echo "n = ", $n, ",",
" Position ", $pos, "\n";
$n = 12;
$pos = findPosition($n);
if(($pos == -1) == true)
echo "n = ", $n, ",",
" Invalid number", "\n";
else
echo "n =", $n, ",",
972
Chapter 157. Find position of the only set bit
Python3
973
Chapter 157. Find position of the only set bit
return pos;
# Driver Code
n = 16;
pos = findPosition(n);
if (pos == -1):
print("n =", n, ", Invalid number");
else:
print("n =", n, ", Position ", pos);
n = 12;
pos = findPosition(n);
if (pos == -1):
print("n =", n, ", Invalid number");
else:
print("n =", n, ", Position ", pos);
n = 128;
pos = findPosition(n);
if (pos == -1):
print("n =", n, ", Invalid number");
else:
print("n =", n," , Position ", pos);
# This code is contributed by mits
Output :
n = 16, Position 5
n = 12, Invalid number
n = 128, Position 8
Following is another method for this problem. The idea is to one by one right shift the
set bit of given number ‘n’ until ‘n’ becomes 0. Count how many times we shifted to make
‘n’ zero. The final count is position of the set bit.
C
974
Chapter 157. Find position of the only set bit
{
if (!isPowerOfTwo(n))
return -1;
unsigned count = 0;
// One by one move the only set bit to right till it reaches end
while (n)
{
n = n >> 1;
// increment count of shifts
++count;
}
return count;
}
// Driver program to test above function
int main(void)
{
int n = 0;
int pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid numbern", n):
printf("n = %d, Position %d n", n, pos);
n = 12;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid numbern", n):
printf("n = %d, Position %d n", n, pos);
n = 128;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid numbern", n):
printf("n = %d, Position %d n", n, pos);
return 0;
}
PHP
<?php
// PHP program to find position of
// only set bit in a given number
// A utility function to check
// whether n is power of 2 or not
function isPowerOfTwo($n)
975
Chapter 157. Find position of the only set bit
{
return $n && (! ($n & ($n - 1)));
}
// Returns position of the
// only set bit in 'n'
function findPosition($n)
{
if (!isPowerOfTwo($n))
return -1;
$count = 0;
// One by one move the only set
// bit to right till it reaches end
while ($n)
{
$n = $n >> 1;
// increment count of shifts
++$count;
}
return $count;
}
// Driver Code
$n = 0;
$pos = findPosition($n);
if(($pos == -1) == true)
echo "n = ", $n, ",",
" Invalid number", "\n";
else
echo "n = ", $n, ",",
" Position ", $pos, "\n";
$n = 12;
$pos = findPosition($n);
if (($pos == -1) == true)
echo "n = ", $n, ",",
" Invalid number", "\n";
else
echo "n = ", $n,
" Position ", $pos, "\n";
$n = 128;
$pos = findPosition($n);
if(($pos == -1) == true)
976
Chapter 157. Find position of the only set bit
Output :
n = 0, Invalid number
n = 12, Invalid number
n = 128, Position 8
We can also use log base 2 to find the position. Thanks to Arunkumarfor suggesting
this solution.
#include <stdio.h>
unsigned int Log2n(unsigned int n)
{
return (n > 1)? 1 + Log2n(n/2): 0;
}
int isPowerOfTwo(unsigned n)
{
return n && (! (n & (n-1)) );
}
int findPosition(unsigned n)
{
if (!isPowerOfTwo(n))
return -1;
return Log2n(n) + 1;
}
// Driver program to test above function
int main(void)
{
int n = 0;
int pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid numbern", n):
printf("n = %d, Position %d n", n, pos);
977
Chapter 157. Find position of the only set bit
n = 12;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid numbern", n):
printf("n = %d, Position %d n", n, pos);
n = 128;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid numbern", n):
printf("n = %d, Position %d n", n, pos);
return 0;
}
Python3
978
Chapter 157. Find position of the only set bit
PHP
<?php
// PHP program to find position
// of only set bit in a given number
function Log2n($n)
{
return ($n > 1) ? 1 +
Log2n($n / 2) : 0;
}
function isPowerOfTwo($n)
{
return $n && (! ($n &
($n - 1)));
}
function findPosition($n)
{
if (!isPowerOfTwo($n))
return -1;
return Log2n($n) + 1;
}
// Driver Code
$n = 0;
$pos = findPosition($n);
if(($pos == -1) == true)
echo "n =", $n, ", " ,
" Invalid number", "\n";
else
echo "n = ",$n, ",",
" Position n", $pos,"\n";
$n = 12;
$pos = findPosition($n);
if(($pos == -1) == true)
979
Chapter 157. Find position of the only set bit
Output :
n = 0, Invalid number
n = 12, Invalid number
n = 128, Position 8
This article is compiled by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Improved By : jit_t, Mithun Kumar
Source
https://www.geeksforgeeks.org/find-position-of-the-only-set-bit/
980
Chapter 158
E
/
E D
/ /
E D D E
/ / / /
E D D E D E E D
Given level and position of a person in above ancestor tree, find the profession of the person.
Examples :
981
Chapter 158. Find profession in a special family
Method 1 (Recursive)
The idea is based on the fact that profession of a person depends on following two.
1. Profession of parent.
2. Position of node : If position of a node is odd, then its profession is same as its parent.
Else profession is different from its parent.
We recursively find the profession of parent, then use point 2 above to find the profession
of current node.
Below is implementation of above idea.
C++
982
Chapter 158. Find profession in a special family
Java
983
Chapter 158. Find profession in a special family
pos) == 'e')
System.out.println("Engineer");
else
System.out.println("Doctor");
}
}
// This code is contributed
// by anuj_67.
C#
// C# program to find
// profession of a person
// at given level and position
using System;
class GFG
{
// Returns 'e' if profession
// of node at given level
// and position is engineer.
// Else doctor. The function
// assumes that given position
// and level have valid values.
static char findProffesion(int level,
int pos)
{
// Base case
if (level == 1)
return 'e';
// Recursively find parent's
// profession. If parent
// is a doctar, this node
// will be a doctal if it
// is at odd position and an
// engineer if at even position
if (findProffesion(level - 1,
(pos + 1) / 2) == 'd')
return (pos % 2 > 0) ?
'd' : 'e';
// If parent is an engineer,
// then current node will be
// an enginner if at add
// position and doctor if even
984
Chapter 158. Find profession in a special family
// position.
return (pos % 2 > 0) ?
'e' : 'd';
}
// Driver code
public static void Main ()
{
int level = 4, pos = 2;
if(findProffesion(level,
pos) == 'e')
Console.WriteLine("Engineer");
else
Console.WriteLine("Doctor");
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP program to find profession
// of a person at given level
// and position.
// Returns 'e' if profession of
// node at given level and position
// is engineer. Else doctor. The
// function assumes that given
// position and level have valid values.
function findProffesion($level, $pos)
{
// Base case
if ($level == 1)
return 'e';
// Recursively find parent's
// profession. If parent is
// a Doctor, this node will
// be a doctor if it is at
// odd position and an engineer
// if at even position
if (findProffesion($level - 1,
($pos + 1) / 2) == 'd')
return ($pos % 2) ? 'd' : 'e';
985
Chapter 158. Find profession in a special family
Output :
Doctor
Level 1: E
Level 2: ED
Level 3: EDDE
Level 4: EDDEDEED
Level 5: EDDEDEEDDEEDEDDE
Level input isn’t necessary (if we ignore max position limit) because first elements are same.
The result is based on count of 1’s in binary representation of position minus one. If count
of 1’s is even then result is Engineer, else then Doctor.
And of course position limit is 2^(Level-1)
C++
986
Chapter 158. Find profession in a special family
PHP
<?php
// PHP program to find profession
// of a person at given level and position.
// Function to get no of set
// bits in binary representation
// of passed binary no.
function countSetBits($n)
{
$count = 0;
while ($n)
{
987
Chapter 158. Find profession in a special family
Output :
Engineer
988
Chapter 158. Find profession in a special family
Source
https://www.geeksforgeeks.org/find-profession-in-a-hypothetical-special-situation/
989
Chapter 159
Find smallest number n such that n XOR n+1 equals to given k. - GeeksforGeeks
You are given a positive number k, we need to find a positive integer n, such that XOR of
n and n+1 is equal to k. If no such n exist then print -1.
Examples:
Input : 3
Output : 1
Input : 7
Output : 3
Input : 6
Output : -1
990
Chapter 159. Find smallest number n such that n XOR n+1 equals to given k.
C++
Java
991
Chapter 159. Find smallest number n such that n XOR n+1 equals to given k.
Python3
C#
992
Chapter 159. Find smallest number n such that n XOR n+1 equals to given k.
// given n
using System;
class GFG
{
// function to return the required
// n
static int xorCalc(int k)
{
if (k == 1)
return 2;
// if k is of form 2^i-1
if (((k + 1) & k) == 0)
return k / 2;
return 1;
}
// Driver code
public static void Main ()
{
int k = 31;
Console.WriteLine(xorCalc(k));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP to find n such
// that XOR of n and n+1
// is equals to given n
// function to return
// the required n
function xorCalc($k)
{
if ($k == 1)
return 2;
// if k is of form 2^i-1
if ((($k + 1) & $k) == 0)
return floor($k / 2);
993
Chapter 159. Find smallest number n such that n XOR n+1 equals to given k.
return 1;
}
// Driver Code
$k = 31;
echo xorCalc($k);
// This code is contributed by vt_m.
?>
Output:
15
Source
https://www.geeksforgeeks.org/find-smallest-number-n-n-xor-n1-equals-given-k/
994
Chapter 160
A Simple Solution is to run two nested loops. The outer loop picks all elements one by
one and inner loop counts number of occurrences of the element picked by outer loop. Time
complexity of this solution is O(n2 ).
Below is the implementation of the brute force approach :
C++
995
Chapter 160. Find the Number Occurring Odd Number of Times
{
for (int i = 0; i < arr_size; i++) {
int count = 0;
for (int j = 0; j < arr_size; j++)
{
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
// driver code
int main()
{
int arr[] = { 2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
cout << getOddOccurrence(arr, n);
return 0;
}
Java
996
Chapter 160. Find the Number Occurring Odd Number of Times
}
return -1;
}
// driver code
public static void main(String[] args)
{
int arr[] = new int[]{ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
// This code has been contributed by Kamal Rawal
Python3
C#
997
Chapter 160. Find the Number Occurring Odd Number of Times
using System;
class GFG
{
// Funtion to find the element
// occurring odd number of times
static int getOddOccurrence(int []arr, int arr_size)
{
for (int i = 0; i < arr_size; i++) {
int count = 0;
for (int j = 0; j < arr_size; j++) {
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
// Driver code
public static void Main()
{
int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.Write(getOddOccurrence(arr, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to find the
// element occurring odd
// number of times
// Function to find the element
// occurring odd number of times
function getOddOccurrence(&$arr, $arr_size)
{
$count = 0;
for ($i = 0;
$i < $arr_size; $i++)
{
998
Chapter 160. Find the Number Occurring Odd Number of Times
for ($j = 0;
$j < $arr_size; $j++)
{
if ($arr[$i] == $arr[$j])
$count++;
}
if ($count % 2 != 0)
return $arr[$i];
}
return -1;
}
// Driver code
$arr = array(2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2);
$n = sizeof($arr);
// Function calling
echo(getOddOccurrence($arr, $n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output :
A Better Solution is to use Hashing. Use array elements as key and their counts as value.
Create an empty hash table. One by one traverse the given array elements and store counts.
Time complexity of this solution is O(n). But it requires extra space for hashing.
Program :
Java
999
Chapter 160. Find the Number Occurring Odd Number of Times
{
HashMap<Integer,Integer> hmap = new HashMap<>();
// Putting all elements into the HashMap
for(int i = 0; i < n; i++)
{
if(hmap.containsKey(arr[i]))
{
int val = hmap.get(arr[i]);
// If array element is already present then
// increase the count of that element.
hmap.put(arr[i], val + 1);
}
else
// if array element is not present then put
// element into the HashMap and initialize
// the count to one.
hmap.put(arr[i], 1);
}
// Checking for odd occurrence of each element present
// in the HashMap
for(Integer a:hmap.keySet())
{
if(hmap.get(a) % 2 != 0)
return a;
}
return -1;
}
// driver code
public static void main(String[] args)
{
int arr[] = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
// This code is contributed by Kamal Rawal
Output :
The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives
1000
Chapter 160. Find the Number Occurring Odd Number of Times
us odd occurring element. Please note that XOR of two elements is 0 if both elements are
same and XOR of a number x with 0 is x.
Below is the implementation of the above approach.
C++
// C program to find the element
// occurring odd number of times
#include <stdio.h>
// Function to find element occurring
// odd number of times
int getOddOccurrence(int ar[], int ar_size)
{
int res = 0;
1001
Chapter 160. Find the Number Occurring Odd Number of Times
Java
Python
1002
Chapter 160. Find the Number Occurring Odd Number of Times
C#
1003
Chapter 160. Find the Number Occurring Odd Number of Times
PHP
<?php
// PHP program to find the
// element occurring odd
// number of times
// Function to find element
// occurring odd number of times
function getOddOccurrence(&$ar, $ar_size)
{
$res = 0;
for ($i = 0; $i < $ar_size; $i++)
$res = $res ^ $ar[$i];
return $res;
}
// Driver Code
$ar = array(2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2);
$n = sizeof($ar);
// Function calling
echo(getOddOccurrence($ar, $n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output :
Source
https://www.geeksforgeeks.org/find-the-number-occurring-odd-number-of-times/
1004
Chapter 161
We can use sorting to do it in O(nLogn) time. We can also use hashing, it has the worst
case time complexity of O(n), but requires extra space.
The idea is to use bitwise operators for a solution that is O(n) time and uses O(1) extra
space. The solution is not easy like other XOR based solutions, because all elements appear
odd number of times here. The idea is taken from here.
Run a loop for all elements in array. At the end of every iteration, maintain following two
values.
ones: The bits that have appeared 1st time or 4th time or 7th time .. etc.
twos: The bits that have appeared 2nd time or 5th time or 8th time .. etc.
Finally, we return the value of ‘ones’
How to maintain the values of ‘ones’ and ‘twos’?
‘ones’ and ‘twos’ are initialized as 0. For every new element in array, find out the common
set bits in the new element and previous value of ‘ones’. These common set bits are actually
the bits that should be added to ‘twos’. So do bitwise OR of the common set bits with ‘twos’.
‘twos’ also gets some extra bits that appear third time. These extra bits are removed later.
1005
Chapter 161. Find the element that appears once
Update ‘ones’ by doing XOR of new element with previous value of ‘ones’. There may be
some bits which appear 3rd time. These extra bits are also removed later.
Both ‘ones’ and ‘twos’ contain those extra bits which appear 3rd time. Remove these extra
bits by finding out common set bits in ‘ones’ and ‘twos’.
C/C++
#include <stdio.h>
int getSingle(int arr[], int n)
{
int ones = 0, twos = 0 ;
int common_bit_mask;
// Let us take the example of {3, 3, 2, 3} to understand this
for( int i=0; i< n; i++ )
{
/* The expression "one & arr[i]" gives the bits that are
there in both 'ones' and new element from arr[]. We
add these bits to 'twos' using bitwise OR
Value of 'twos' will be set as 0, 3, 3 and 1 after 1st,
2nd, 3rd and 4th iterations respectively */
twos = twos | (ones & arr[i]);
/* XOR the new bits with previous 'ones' to get all bits
appearing odd number of times
Value of 'ones' will be set as 3, 0, 2 and 3 after 1st,
2nd, 3rd and 4th iterations respectively */
ones = ones ^ arr[i];
/* The common bits are those bits which appear third time
So these bits should not be there in both 'ones' and 'twos'.
common_bit_mask contains all these bits as 0, so that the bits can
be removed from 'ones' and 'twos'
Value of 'common_bit_mask' will be set as 00, 00, 01 and 10
after 1st, 2nd, 3rd and 4th iterations respectively */
common_bit_mask = ~(ones & twos);
/* Remove common bits (the bits that appear third time) from 'ones'
Value of 'ones' will be set as 3, 0, 0 and 2 after 1st,
1006
Chapter 161. Find the element that appears once
Java
1007
Chapter 161. Find the element that appears once
Python3
1008
Chapter 161. Find the element that appears once
C#
1009
Chapter 161. Find the element that appears once
PHP
<?php
function getSingle($arr, $n)
{
1010
Chapter 161. Find the element that appears once
$ones = 0; $twos = 0 ;
$common_bit_mask;
// Let us take the example of
// {3, 3, 2, 3} to understand this
for($i = 0; $i < $n; $i++ )
{
/* The expression "one & arr[i]"
gives the bits that are there in
both 'ones' and new element from
arr[]. We add these bits to 'twos'
using bitwise OR
Value of 'twos' will be set as 0,
3, 3 and 1 after 1st, 2nd, 3rd
and 4th iterations respectively */
$twos = $twos | ($ones & $arr[$i]);
/* XOR the new bits with previous
'ones' to get all bits appearing
odd number of times
Value of 'ones' will be set as 3,
0, 2 and 3 after 1st, 2nd, 3rd and
4th iterations respectively */
$ones = $ones ^ $arr[$i];
/* The common bits are those bits
which appear third time. So these
bits should not be there in both
'ones' and 'twos'. common_bit_mask
contains all these bits as 0, so
that the bits can be removed from
'ones' and 'twos'
Value of 'common_bit_mask' will be
set as 00, 00, 01 and 10 after 1st,
2nd, 3rd and 4th iterations respectively */
$common_bit_mask = ~($ones & $twos);
/* Remove common bits (the bits
that appear third time) from 'ones'
Value of 'ones' will be set as 3,
0, 0 and 2 after 1st, 2nd, 3rd
and 4th iterations respectively */
1011
Chapter 161. Find the element that appears once
Output :
#include <stdio.h>
1012
Chapter 161. Find the element that appears once
#define INT_SIZE 32
int getSingle(int arr[], int n)
{
// Initialize result
int result = 0;
int x, sum;
// Iterate through every bit
for (int i = 0; i < INT_SIZE; i++)
{
// Find sum of set bits at ith position in all
// array elements
sum = 0;
x = (1 << i);
for (int j=0; j< n; j++ )
{
if (arr[j] & x)
sum++;
}
// The bits with sum not multiple of 3, are the
// bits of element with single occurrence.
if (sum % 3)
result |= x;
}
return result;
}
// Driver program to test above function
int main()
{
int arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7};
int n = sizeof(arr) / sizeof(arr[0]);
printf("The element with single occurrence is %d ",
getSingle(arr, n));
return 0;
}
Java
1013
Chapter 161. Find the element that appears once
Python 3
1014
Chapter 161. Find the element that appears once
result = 0
# Iterate through every bit
for i in range(0, INT_SIZE) :
# Find sum of set bits
# at ith position in all
# array elements
sm = 0
x = (1 << i)
for j in range(0, n) :
if (arr[j] & x) :
sm = sm + 1
# The bits with sum not
# multiple of 3, are the
# bits of element with
# single occurrence.
if (sm % 3) :
result = result | x
return result
# Driver program
arr = [12, 1, 12, 3, 12, 1, 1, 2, 3, 2, 2, 3, 7]
n = len(arr)
print("The element with single occurrence is "
,getSingle(arr, n))
# This code is contributed
# by Nikita Tiwari.
C#
1015
Chapter 161. Find the element that appears once
int x, sum;
// Iterate through every bit
for(int i = 0; i < INT_SIZE; i++)
{
// Find sum of set bits at ith
// position in all array elements
sum = 0;
x = (1 << i);
for(int j = 0; j < n; j++)
{
if((arr[j] & x) == 0)
sum++;
}
// The bits with sum not multiple
// of 3, are the bits of element
// with single occurrence.
if ((sum % 3) == 0)
result |= x;
}
return result;
}
// Driver Code
public static void Main()
{
int []arr = {12, 1, 12, 3, 12, 1,
1, 2, 3, 2, 2, 3, 7};
int n = arr.Length;
Console.WriteLine("The element with single " +
"occurrence is " + getSingle(arr, n));
}
}
// This code is contributed ny vt_m.
PHP
<?php
// PHP code to find the element
// that occur only once
$INT_SIZE= 32;
function getSingle($arr, $n)
{
global $INT_SIZE;
1016
Chapter 161. Find the element that appears once
// Initialize result
$result = 0;
$x; $sum;
// Iterate through every bit
for ($i = 0; $i < $INT_SIZE; $i++)
{
// Find sum of set bits at ith
// position in all array elements
$sum = 0;
$x = (1 << $i);
for ($j = 0; $j < $n; $j++ )
{
if ($arr[$j] & $x)
$sum++;
}
// The bits with sum not multiple
// of 3, are the bits of element
// with single occurrence.
if ($sum % 3)
$result |= $x;
}
return $result;
}
// Driver Code
$arr = array (12, 1, 12, 3, 12, 1,
1, 2, 3, 2, 2, 3, 7);
$n = sizeof($arr);
echo "The element with single occurrence is ",
getSingle($arr, $n);
// This code is contributed by ajit
?>
Output :
Another approach suggested by Abhishek Sharma 44. Add each number once and multiply
the sum by 3, we will get thrice the sum of each element of the array. Store it as thrice_sum.
Subtract the sum of the whole array from the thrice_sum and divide the result by 2. The
number we get is the required number (which appears once in the array).
1017
Chapter 161. Find the element that appears once
Array [] : [a, a, a, b, b, b, c, c, c, d]
Mathematical Equation = ( 3*(a+b+c+d) – (a + a + a + b + b + b + c + c + c + d) ) /
2
In more simple words: ( 3*(sum_of_array_without_duplicates) – (sum_of_array) ) / 2
As we know that set does not contain any duplicate element, we will be using set here.
Below is the implementation of above approach:
Python3
Output :
This article is compiled by Sumit Jain and reviewed by GeeksforGeeks team. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
Improved By : jit_t
1018
Chapter 161. Find the element that appears once
Source
https://www.geeksforgeeks.org/find-the-element-that-appears-once/
1019
Chapter 162
Find the largest number with n set and m unset bits - GeeksforGeeks
Given two non-negative numbers n and m. The problem is to find the largest number
having n number of set bits and m number of unset bits in its binary representation.
Note : 0 bits before leading 1 (or leftmost 1) in binary representation are counted
Contraints: 1 <= n, 0 <= m, (m+n) <= 31
Examples :
Input : n = 2, m = 2
Output : 12
(12)10 = (1100)2
We can see that in the binary representation of 12
there are 2 set and 2 unsets bits and it is the largest number.
Input : n = 4, m = 1
Output : 30
1. Calculate num = (1 << (n + m)) – 1. This will produce a number num having (n
+ m) number of bits and all are set.
2. Now, toggle the last m bits of num and then return the toggled number. Refer this
post.
C/C++
1020
Chapter 162. Find the largest number with n set and m unset bits
Java
1021
Chapter 162. Find the largest number with n set and m unset bits
class GFG
{
// Function to toggle the last m bits
static int toggleLastMBits(int n, int m)
{
// if no bits are required to be toggled
if (m == 0)
return n;
// calculating a number 'num' having 'm' bits
// and all are set
int num = (1 << m) - 1;
// toggle the last m bits and return the number
return (n ^ num);
}
// Function to find the largest number
// with n set and m unset bits
static int largeNumWithNSetAndMUnsetBits(int n, int m)
{
// calculating a number 'num' having '(n+m)' bits
// and all are set
int num = (1 << (n + m)) - 1;
// required largest number
return toggleLastMBits(num, m);
}
// driver program
public static void main (String[] args)
{
int n = 2, m = 2;
System.out.println(largeNumWithNSetAndMUnsetBits(n, m));
}
}
// Contributed by Pramod Kumar
Python3
# Python implementation to
# find the largest number
# with n set and m unset bits
# function to toggle
# the last m bits
1022
Chapter 162. Find the largest number with n set and m unset bits
def toggleLastMBits(n,m):
# if no bits are required
# to be toggled
if (m == 0):
return n
# calculating a number
# 'num' having 'm' bits
# and all are set
num = (1 << m) - 1
# toggle the last m bits
# and return the number
return (n ^ num)
# function to find
# the largest number
# with n set and m unset bits
def largeNumWithNSetAndMUnsetBits(n,m):
# calculating a number
# 'num' having '(n+m)' bits
# and all are set
num = (1 << (n + m)) - 1
# required largest number
return toggleLastMBits(num, m)
# Driver code
n = 2
m = 2
print(largeNumWithNSetAndMUnsetBits(n, m))
# This code is contributed
# by Anant Agarwal.
C#
1023
Chapter 162. Find the largest number with n set and m unset bits
PHP
<?php
// PHP implementation to find
// the largest number with n
// set and m unset bits
// function to toggle
// the last m bits
function toggleLastMBits($n, $m)
1024
Chapter 162. Find the largest number with n set and m unset bits
{
// if no bits are required
// to be toggled
if ($m == 0)
return $n;
// calculating a number 'num'
// having 'm' bits and all are set
$num = (1 << $m) - 1;
// toggle the last m bits
// and return the number
return ($n ^ $num);
}
// function to find the largest number
// with n set and m unset bits
function largeNumWithNSetAndMUnsetBits($n,
$m)
{
// calculating a number 'num'
// having '(n+m)' bits and all are set
$num = (1 << ($n + $m)) - 1;
// required largest number
return toggleLastMBits($num, $m);
}
// Driver Code
$n = 2; $m = 2;
echo largeNumWithNSetAndMUnsetBits($n, $m);
// This code is contributed by vt_m.
?>
Output :
12
For greater values of n and m, you can use long int and long long int datatypes to
generate the required number.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-largest-number-n-set-m-unset-bits/
1025
Chapter 163
A Simple Solution is to use two loops to find XOR of all subarrays and return the maxi-
mum.
C++
1026
Chapter 163. Find the maximum subarray XOR in a given array
{
int ans = INT_MIN; // Initialize result
// Pick starting points of subarrays
for (int i=0; i<n; i++)
{
int curr_xor = 0; // to store xor of current subarray
// Pick ending points of subarrays starting with i
for (int j=i; j<n; j++)
{
curr_xor = curr_xor ^ arr[j];
ans = max(ans, curr_xor);
}
}
return ans;
}
// Driver program to test above functions
int main()
{
int arr[] = {8, 1, 2, 12};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n);
return 0;
}
Java
1027
Chapter 163. Find the maximum subarray XOR in a given array
return ans;
}
// Driver program to test above functions
public static void main(String args[])
{
int arr[] = {8, 1, 2, 12};
int n = arr.length;
System.out.println("Max subarray XOR is " +
maxSubarrayXOR(arr, n));
}
}
//This code is contributed by Sumit Ghosh
Python3
1028
Chapter 163. Find the maximum subarray XOR in a given array
C#
PHP
1029
Chapter 163. Find the maximum subarray XOR in a given array
<?php
// A simple PHP program to
// find max subarray XOR
function maxSubarrayXOR($arr, $n)
{
// Initialize result
$ans = PHP_INT_MIN;
// Pick starting points
// of subarrays
for ($i = 0; $i < $n; $i++)
{
// to store xor of
// current subarray
$curr_xor = 0;
// Pick ending points of
// subarrays starting with i
for ($j = $i; $j < $n; $j++)
{
$curr_xor = $curr_xor ^ $arr[$j];
$ans = max($ans, $curr_xor);
}
}
return $ans;
}
// Driver Code
$arr = array(8, 1, 2, 12);
$n = count($arr);
echo "Max subarray XOR is "
, maxSubarrayXOR($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
1030
Chapter 163. Find the maximum subarray XOR in a given array
1031
Chapter 163. Find the maximum subarray XOR in a given array
// Utility function tp create a Trie node
TrieNode *newNode()
{
TrieNode *temp = new TrieNode;
temp->value = 0;
temp->arr[0] = temp->arr[1] = NULL;
return temp;
}
// Inserts pre_xor to trie with given root
void insert(TrieNode *root, int pre_xor)
{
TrieNode *temp = root;
// Start from the msb, insert all bits of
// pre_xor into Trie
for (int i=INT_SIZE-1; i>=0; i--)
{
// Find current bit in given prefix
bool val = pre_xor & (1<<i);
// Create a new node if needed
if (temp->arr[val] == NULL)
temp->arr[val] = newNode();
temp = temp->arr[val];
}
// Store value at leaf node
temp->value = pre_xor;
}
// Finds the maximum XOR ending with last number in
// prefix XOR 'pre_xor' and returns the XOR of this maximum
// with pre_xor which is maximum XOR ending with last element
// of pre_xor.
int query(TrieNode *root, int pre_xor)
{
TrieNode *temp = root;
for (int i=INT_SIZE-1; i>=0; i--)
{
// Find current bit in given prefix
bool val = pre_xor & (1<<i);
// Traverse Trie, first look for a
// prefix that has opposite bit
if (temp->arr[1-val]!=NULL)
1032
Chapter 163. Find the maximum subarray XOR in a given array
temp = temp->arr[1-val];
// If there is no prefix with opposite
// bit, then look for same bit.
else if (temp->arr[val] != NULL)
temp = temp->arr[val];
}
return pre_xor^(temp->value);
}
// Returns maximum XOR value of a subarray in arr[0..n-1]
int maxSubarrayXOR(int arr[], int n)
{
// Create a Trie and insert 0 into it
TrieNode *root = newNode();
insert(root, 0);
// Initialize answer and xor of current prefix
int result = INT_MIN, pre_xor =0;
// Traverse all input array element
for (int i=0; i<n; i++)
{
// update current prefix xor and insert it into Trie
pre_xor = pre_xor^arr[i];
insert(root, pre_xor);
// Query for current prefix xor in Trie and update
// result if required
result = max(result, query(root, pre_xor));
}
return result;
}
// Driver program to test above functions
int main()
{
int arr[] = {8, 1, 2, 12};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n);
return 0;
}
Java
1033
Chapter 163. Find the maximum subarray XOR in a given array
{
// Assumed int size
static final int INT_SIZE = 32;
// A Trie Node
static class TrieNode
{
int value; // Only used in leaf nodes
TrieNode[] arr = new TrieNode[2];
public TrieNode() {
value = 0;
arr[0] = null;
arr[1] = null;
}
}
static TrieNode root;
// Inserts pre_xor to trie with given root
static void insert(int pre_xor)
{
TrieNode temp = root;
// Start from the msb, insert all bits of
// pre_xor into Trie
for (int i=INT_SIZE-1; i>=0; i--)
{
// Find current bit in given prefix
int val = (pre_xor & (1<<i)) >=1 ? 1 : 0;
// Create a new node if needed
if (temp.arr[val] == null)
temp.arr[val] = new TrieNode();
temp = temp.arr[val];
}
// Store value at leaf node
temp.value = pre_xor;
}
// Finds the maximum XOR ending with last number in
// prefix XOR 'pre_xor' and returns the XOR of this
// maximum with pre_xor which is maximum XOR ending
// with last element of pre_xor.
static int query(int pre_xor)
{
TrieNode temp = root;
for (int i=INT_SIZE-1; i>=0; i--)
1034
Chapter 163. Find the maximum subarray XOR in a given array
{
// Find current bit in given prefix
int val = (pre_xor & (1<<i)) >= 1 ? 1 : 0;
// Traverse Trie, first look for a
// prefix that has opposite bit
if (temp.arr[1-val] != null)
temp = temp.arr[1-val];
// If there is no prefix with opposite
// bit, then look for same bit.
else if (temp.arr[val] != null)
temp = temp.arr[val];
}
return pre_xor^(temp.value);
}
// Returns maximum XOR value of a subarray in
// arr[0..n-1]
static int maxSubarrayXOR(int arr[], int n)
{
// Create a Trie and insert 0 into it
root = new TrieNode();
insert(0);
// Initialize answer and xor of current prefix
int result = Integer.MIN_VALUE;
int pre_xor =0;
// Traverse all input array element
for (int i=0; i<n; i++)
{
// update current prefix xor and insert it
// into Trie
pre_xor = pre_xor^arr[i];
insert(pre_xor);
// Query for current prefix xor in Trie and
// update result if required
result = Math.max(result, query(pre_xor));
}
return result;
}
// Driver program to test above functions
public static void main(String args[])
{
1035
Chapter 163. Find the maximum subarray XOR in a given array
Output:
Exercise: Extend the above solution so that it also prints starting and ending indexes of
subarray with maximum value (Hint: we can add one more field to Trie node to achieve
this)
This article is contributed by Romil Punetha. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007, vt_m
Source
https://www.geeksforgeeks.org/find-the-maximum-subarray-xor-in-a-given-array/
1036
Chapter 164
Note that this problem is different from the maximum subarray XOR. Here we need to find
subset instead of subarray.
A Simple Solution is to generate all possible subsets of given set, find XOR of every subset
and return the subset with maximum XOR.
Below is an Efficient Algorithm that works in O(n) time.
The idea is based on below facts:
1037
Chapter 164. Find the maximum subset XOR of a given set
1. Number of bits to represent all elements is fixed which is 32 bits for integer in most
of the compilers.
2. If maximum element has Most Significant Bit MSB at position i, then result is at least
2i
1038
Chapter 164. Find the maximum subset XOR of a given set
{
// Initialize index of
// maximum element and
// the maximum element
int maxInd = index;
int maxEle = INT_MIN;
for (int j = index; j < n; j++)
{
// If i'th bit of set[j]
// is set and set[j] is
// greater than max so far.
if ( (set[j] & (1 << i)) != 0
&& set[j] > maxEle )
maxEle = set[j], maxInd = j;
}
// If there was no
// element with i'th
// bit set, move to
// smaller i
if (maxEle == INT_MIN)
continue;
// Put maximum element
// with i'th bit set
// at index 'index'
swap(set[index], set[maxInd]);
// Update maxInd and
// increment index
maxInd = index;
// Do XOR of set[maxIndex]
// with all numbers having
// i'th bit as set.
for (int j=0; j<n; j++)
{
// XOR set[maxInd] those
// numbers which have the
// i'th bit set
if (j != maxInd &&
(set[j] & (1 << i)) != 0)
set[j] = set[j] ^ set[maxInd];
}
// Increment index of
// chosen elements
index++;
1039
Chapter 164. Find the maximum subset XOR of a given set
}
// Final result is
// XOR of all elements
int res = 0;
for (int i = 0; i < n; i++)
res ^= set[i];
return res;
}
// Driver program
int main()
{
int set[] = {9, 8, 5};
int n = sizeof(set) / sizeof(set[0]);
cout << "Max subset XOR is ";
cout << maxSubarrayXOR(set, n);
return 0;
}
Java
1040
Chapter 164. Find the maximum subset XOR of a given set
1041
Chapter 164. Find the maximum subset XOR of a given set
Python3
1042
Chapter 164. Find the maximum subset XOR of a given set
1043
Chapter 164. Find the maximum subset XOR of a given set
C#
// C# program to find
// maximum XOR subset
using System;
class GFG
{
// Number of bits to
// represent int
static int INT_BITS = 32;
// Function to return
// maximum XOR subset
// in set[]
static int maxSubarrayXOR(int []set,
int n)
{
// Initialize index of
// chosen elements
int index = 0;
// Traverse through all
// bits of integer
1044
Chapter 164. Find the maximum subset XOR of a given set
1045
Chapter 164. Find the maximum subset XOR of a given set
// XOR set[maxInd] those
// numbers which have the
// i'th bit set
if (j != maxInd && (set[j] &
(1 << i)) != 0)
set[j] = set[j] ^ set[maxInd];
}
// Increment index of
// chosen elements
index++;
}
// Final result is
// XOR of all elements
int res = 0;
for (int i = 0; i < n; i++)
res ^= set[i];
return res;
}
// Driver code
public static void Main()
{
int []set = {9, 8, 5};
int n = set.Length;
Console.Write("Max subset XOR is ");
Console.Write(maxSubarrayXOR(set, n));
}
}
// This code is contributed by Sam007.
Output:
Illustration:
1046
Chapter 164. Find the maximum subset XOR of a given set
The 4th bit is set in set[0] i.e. 9 and this is the maximum
element with 4th bit set. So we choose this element and check
if any other number has the same bit set. If yes, we XOR that
number with 9. The element set[1], i.e., 8 also has 4'th bit
set. Now set[] becomes {9, 1, 5}. We add 9 to the list of
chosen elements by incrementing 'index'
We move further and find the maximum number with 3rd bit set
which is set[2] i.e. 5 No other number in the array has 3rd
bit set. 5 is also added to the list of chosen element.
We then iterate for bit 2 (no number for this) and then for
1 which is 1. But numbers 9 and 5 have the 1st bit set. Thus
we XOR 9 and 5 with 1 and our set becomes (8, 1, 4)
Source
https://www.geeksforgeeks.org/find-maximum-subset-xor-given-set/
1047
Chapter 165
Find the missing element in an array of integers represented in binary format - Geeks-
forGeeks
Given N strings which represents all integers from 0 to N in binary format except any one.
The task is to find the missing number. Input consists of an array of strings where array
elements are represented in binary format.
Examples:
Approach:
• An imbalance of 1’s and 0’s in the least significant bits of the numbers can be observed
in the N integers given. Since one number is missing either a 0 or 1 from the LSB is
missing. If the number which is missing has LSB = 0 then count(1) will be greater
than equal to count(0). If LSB of missing number is 1 then count(1) is less than
count(0).
• From the step 1 one can easily determine the LSB of missing number.
• Once determined, discard all the numbers having LSB different from that of the miss-
ing number, i.e., if the missing number has LSB = 0, then discard all the numbers
with LSB = 1 and vice versa.
• Continue the process from step 1 all over again and recur for the next LSB.
1048
Chapter 165. Find the missing element in an array of integers represented in binary
format
• Continue with the above process till all the bits are traversed.
1049
Chapter 165. Find the missing element in an array of integers represented in binary
format
1050
Chapter 165. Find the missing element in an array of integers represented in binary
format
1051
Chapter 165. Find the missing element in an array of integers represented in binary
format
}
// Driver Code.
int main()
{
// a corresponds to the input array which
// is a list of binary numbers
list<BitInteger> a = { BitInteger("0000"), BitInteger("0001"),
BitInteger("0010"), BitInteger("0100"),
BitInteger("0101") };
int missing1 = findMissing(a);
cout << missing1 << "\n";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-the-missing-element-in-an-array-of-integers-represented-in-binary-format/
1052
Chapter 166
Input : 1
Output : 1
1st Number whose binary representation
is palindrome is 1 (1)
Input : 9
Output : 27
9th Number whose binary representation
is palindrome is 27 (11011)
Method 1: Naive
Naive approach would be, traverse through all the integers from 1 to 2^31 – 1 and increment
palindrome count, if the number is palindrome. When the palindrome count reaches the
required n, break the loop and return the current integer.
1053
Chapter 166. Find the n-th number whose binary representation is a palindrome
1054
Chapter 166. Find the n-th number whose binary representation is a palindrome
Java
1055
Chapter 166. Find the n-th number whose binary representation is a palindrome
{
count++;
x = x >> 1;
}
return count;
}
/* Finds whether the integer
in binary representation is
palindrome or not*/
static int isBinPalindrome(int x)
{
int l = leftmostSetBit(x);
int r = 1;
// One by one compare bits
while (l > r)
{
// Compare left and right
// bits and converge
if (isKthBitSet(x, l) !=
isKthBitSet(x, r))
return 0;
l--;
r++;
}
return 1;
}
static int findNthPalindrome(int n)
{
int pal_count = 0;
/* Start from 1, traverse
through all the integers */
int i = 0;
for (i = 1; i <= INT_MAX; i++)
{
if (isBinPalindrome(i) > 0)
{
pal_count++;
}
/* If we reach n,
break the loop */
if (pal_count == n)
break;
1056
Chapter 166. Find the n-th number whose binary representation is a palindrome
}
return i;
}
// Driver code
public static void main (String[] args)
{
int n = 9;
System.out.println(findNthPalindrome(n));
}
}
// This code is contributed
// by anuj_67.
27
Time complexity of this solution is O(x) where x is resultant number. Note that value of x
is generally much larger than n.
Method 2: Constructing the nth palindrome
We can construct the nth binary palindrome in its binary representation directly using the
below approach.
If we observe first few binary palindromes
* | nth Binary |
n | Palindrome | Group
| |
--------------------------- Group 0
1 ---> 1 (1)
1057
Chapter 166. Find the n-th number whose binary representation is a palindrome
7 ---> 10001
8 ---> 10101
9 ---> 11011
10 ---> 11111
15 ---> 1000001
16 ---> 1001001
17 ---> 1010101
18 ---> 1011101
19 ---> 1100011
20 ---> 1101011
21 ---> 1110111
22 ---> 1111111
--------------------
Algorithm:
1) We can divide the set of palindrome numbers into some groups.
2) n-th group will have (2^(n-1) + 2^n = 3 * 2 ^(n-1) ) number of binary palindromes
3) With the given number, we can find the group to which it belongs to and the offset in
that group.
4) As the leading zeros are not to be considered, we should use bit 1 as the starting bit and
ending bit of the number in binary representation
5) And we will fill other bits based on the groupno and groupoffset
6) Based on the offset, we can find which bit should be inserted at the middle (|(nothing)
or 0 or 1) and
which number(in binary form) (1 or 2 or 3 or 4 or ..) should be placed in both directions
1058
Chapter 166. Find the n-th number whose binary representation is a palindrome
from middle
Consider Below Example
1059
Chapter 166. Find the n-th number whose binary representation is a palindrome
1060
Chapter 166. Find the n-th number whose binary representation is a palindrome
1061
Chapter 166. Find the n-th number whose binary representation is a palindrome
Output :
27
1062
Chapter 166. Find the n-th number whose binary representation is a palindrome
Source
https://www.geeksforgeeks.org/find-n-th-number-whose-binary-representation-palindrome/
1063
Chapter 167
Find the smallest number with n set and m unset bits - GeeksforGeeks
Given two non-negative numbers n and m. The problem is to find the smallest number
having n number of set bits and m number of unset bits in its binary representation.
Constraints: 1 <= n, 0 <= m, (m+n) <= 31
Note : 0 bits before leading 1 (or leftmost 1) in binary representation are counted
Examples:
Input : n = 2, m = 2
Output : 9
(9)10 = (1001)2
We can see that in the binary representation of 9
there are 2 set and 2 unsets bits and it is the
smallest number.
Input : n = 4, m = 1
Output : 23
1. Calculate num = (1 << (n + m)) – 1. This will produce a number num having (n
+ m) number of bits and all are set.
2. Now, toggle bits in the range from n to (n+m-1) in num, i.e, to toggle bits from
the rightmost nth bit to the rightmost (n+m-1)th bit and then return the toggled
number. Refer this post.
C/C++
1064
Chapter 167. Find the smallest number with n set and m unset bits
Java
1065
Chapter 167. Find the smallest number with n set and m unset bits
Python3
1066
Chapter 167. Find the smallest number with n set and m unset bits
C#
1067
Chapter 167. Find the smallest number with n set and m unset bits
{
// Function to toggle bits in the given range
static int toggleBitsFromLToR(int n, int l, int r)
{
// for invalid range
if (r < l)
return n;
// calculating a number 'num' having 'r'
// number of bits and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// toggle bits in the range l to r in 'n'
// and return the number
return (n ^ num);
}
// Function to find the smallest number
// with n set and m unset bits
static int smallNumWithNSetAndMUnsetBits(int n, int m)
{
// calculating a number 'num' having '(n+m)' bits
// and all are set
int num = (1 << (n + m)) - 1;
// required smallest number
return toggleBitsFromLToR(num, n, n + m - 1);
}
// Driver program
public static void Main ()
{
int n = 2, m = 2;
Console.Write(smallNumWithNSetAndMUnsetBits(n, m));
}
}
// This code is contributed by Sam007
Output:
For greater values of n and m, you can use long int and long long int datatypes to
generate the required number.
1068
Chapter 167. Find the smallest number with n set and m unset bits
Source
https://www.geeksforgeeks.org/find-smallest-number-n-set-m-unset-bits/
1069
Chapter 168
xor = arr[0]^arr[1]^arr[2].....arr[n-1]
All the bits that are set in xor will be set in one non-repeating element (x or y) and not in
other. So if we take any set bit of xor and divide the elements of the array in two sets – one
set of elements with same bit set and other set with same bit not set. By doing so, we will
get x in one set and y in another set. Now if we do XOR of all the elements in first set, we
will get first non-repeating element, and by doing same in other set we will get the second
non-repeating element.
1070
Chapter 168. Find the two non-repeating elements in an array of repeating elements
Implementation:
#include <stdio.h>
#include <stdlib.h>
/* This finction sets the values of *x and *y to nonr-epeating
elements in an array arr[] of size n*/
void get2NonRepeatingNos(int arr[], int n, int *x, int *y)
{
int xor = arr[0]; /* Will hold xor of all elements */
int set_bit_no; /* Will have only single set bit of xor */
int i;
*x = 0;
*y = 0;
/* Get the xor of all elements */
for(i = 1; i < n; i++)
xor ^= arr[i];
/* Get the rightmost set bit in set_bit_no */
set_bit_no = xor & ~(xor-1);
/* Now divide elements in two sets by comparing rightmost set
bit of xor with bit at same position in each element. */
for(i = 0; i < n; i++)
{
if(arr[i] & set_bit_no)
*x = *x ^ arr[i]; /*XOR of first set */
else
*y = *y ^ arr[i]; /*XOR of second set*/
}
}
/* Driver program to test above function */
int main()
{
int arr[] = {2, 3, 7, 9, 11, 2, 3, 11};
1071
Chapter 168. Find the two non-repeating elements in an array of repeating elements
Source
https://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/
1072
Chapter 169
Let’s start the solution step by step. We have total of three option for the XOR of array
and this game.
1. XOR of array is already 0: In this case Alice will unable to make a move and
hence Alice is winner.
2. XOR of array is not zero: Now, in this case we have two options, either size of
array will be odd or even.
• CASE A: If the array size is odd then for sure Bob will win the game.
• CASE B: If the array size is even then Alice will win the game.
1073
Chapter 169. Find the winner in nim-game
int res = 0;
for (int i = 1; i <= N; i++) {
res ^= a[i];
}
if (res == 0)
return "ALice";
if (N%2 == 0)
return "Alice";
else
return "Bob";
C++
1074
Chapter 169. Find the winner in nim-game
res ^= A[i];
// case when Alice is winner
if (res == 0 || n % 2 == 0)
return "Alice";
// when Bob is winner
else
return "Bob";
}
// driver program
int main()
{
int A[] = { 1, 4, 3, 5 };
int n = siseof(A) / sizeof(A[0]);
cout << "Winner = " << findWinner(A, n);
return 0;
}
Java
1075
Chapter 169. Find the winner in nim-game
System.out.print("Winner = "
+ findWinner(A, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
1076
Chapter 169. Find the winner in nim-game
// case when Alice is winner
if (res == 0 || n % 2 == 0)
return "Alice";
// when Bob is winner
else
return "Bob";
}
//Driver code
public static void Main ()
{
int []A = { 1, 4, 3, 5 };
int n =A.Length;
Console.WriteLine("Winner = "
+ findWinner(A, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP to find nim-game winner
// function to find
// winner of NIM-game
function findWinner($A, $n)
{
$res = 0;
for ($i = 0; $i < $n; $i++)
$res ^= $A[$i];
// case when Alice is winner
if ($res == 0 or $n % 2 == 0)
return "Alice";
// when Bob is winner
else
return "Bob";
}
// Driver Code
$A = array(1, 4, 3, 5 );
$n = count($A);
1077
Chapter 169. Find the winner in nim-game
Output :
Winner = Alice
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-winner-nim-game/
1078
Chapter 170
Given the sum and xor of two numbers X and Y s.t. sum and xor ,
we need to find the numbers minimizing the value of X.
Examples :
Input : sum = 17
xor = 13
Output : X = 2
Y = 15
Let the summation be S and xor be xo. The summation and xor operations both are
commutative in nature. This means that for a corresponding set bit in X if we swap it with
an unset bit at same position in Y, the sum and xor would remain unaffected. The only
affect it would make is that it will reduce the value of X and increase the value of Y.
For example, X = 7 and Y = 10, X+Y = S = 17 and X^Y = xo = 13.
Binary representation of X = 0111
1079
Chapter 170. Find two numbers from their sum and XOR
Using the above equations we can easily compute the required values of X and Y.
C++
1080
Chapter 170. Find two numbers from their sum and XOR
{
unsigned long int S = 17, Xo = 13;
compute(S, Xo);
return 0;
}
Java
1081
Chapter 170. Find two numbers from their sum and XOR
Python3
C#
1082
Chapter 170. Find two numbers from their sum and XOR
class GFG
{
// Function that takes in the
// sum and XOR of two numbers
// and generates the two numbers
// such that the value of X is
// minimized
public static void compute(int S,
int Xo)
{
// If sum becomes less than
// Xor in this case, no
// solution shall exist.
if (S < Xo)
Console.WriteLine("No such " +
"numbers exist");
else
{
// Application of the
// derived formula!
int x = (S - Xo) / 2;
Console.WriteLine("X = "+ x);
Console.WriteLine("Y = "+ (x + Xo));
}
}
// Driver Code
static public void Main ()
{
int S = 17, Xo = 13;
compute(S, Xo);
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to find two numbers
// with given Sum and XOR such that
// value of first number is minimum.
1083
Chapter 170. Find two numbers from their sum and XOR
Output :
X = 2
Y = 15
Source
https://www.geeksforgeeks.org/find-two-numbers-sum-xor/
1084
Chapter 171
Input : n = 13, k = 2
Output : 0
Binary representation of 13 is 1101.
Second bit from right is 0.
Input : n = 14, k = 3
Output : 1
Binary representation of 14 is 1110.
Third bit from right is 1.
1) Find a number with all 0s except k-th position. We get this number using ( 1 << (k-1)
). For example if k = 3, then ( 1 << 2) gives us (00..00100).
2) Do bitwise and of above obtained number with n to find if k-th bit in n is set or not.
C++
1085
Chapter 171. Find value of k-th bit in binary representation
{
cout << (n & (1 << (k-1)));
}
int main()
{
unsigned int n = 13, k = 2;
printKthBit(n, k);
return 0;
}
Java
Python3
1086
Chapter 171. Find value of k-th bit in binary representation
C#
PHP
<?php
// PHP program to find
// k-th bit from right
function printKthBit($n, $k)
{
echo ($n & (1 << ($k - 1)));
}
// Driver Code
$n = 13; $k = 2;
printKthBit($n, $k);
// This code is contributed
// by anuj_67.
?>
Output :
1087
Chapter 171. Find value of k-th bit in binary representation
Source
https://www.geeksforgeeks.org/find-value-k-th-bit-binary-representation/
1088
Chapter 172
Input : 16
Output : 16 is a power of 4
Input : 20
Output : 20 is not a power of 4
1. A simple method is to take log of the given number on base 4, and if we get an integer
then number is power of 4.
2. Another solution is to keep dividing the number by 4, i.e, do n = n/4 iteratively. In any
iteration, if n%4 becomes non-zero and n is not 1 then n is not a power of 4, otherwise n is
a power of 4.
#include<stdio.h>
#define bool int
/* Function to check if x is power of 4*/
bool isPowerOfFour(int n)
{
if(n == 0)
return 0;
1089
Chapter 172. Find whether a given number is a power of 4 or not
while(n != 1)
{
if(n % 4 != 0)
return 0;
n = n / 4;
}
return 1;
}
/*Driver program to test above function*/
int main()
{
int test_no = 64;
if(isPowerOfFour(test_no))
printf("%d is a power of 4", test_no);
else
printf("%d is not a power of 4", test_no);
getchar();
}
Java
1090
Chapter 172. Find whether a given number is a power of 4 or not
Python3
C#
1091
Chapter 172. Find whether a given number is a power of 4 or not
if (n == 0)
return 0;
while (n != 1) {
if (n % 4 != 0)
return 0;
n = n / 4;
}
return 1;
}
// Driver code
public static void Main()
{
int test_no = 64;
if (isPowerOfFour(test_no) == 1)
Console.Write(test_no +
" is a power of 4");
else
Console.Write(test_no +
" is not a power of 4");
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP code to check if given
// number is power of 4 or not
// Function to check if
// x is power of 4
function isPowerOfFour($n)
{
if($n == 0)
return 0;
while($n != 1)
{
if($n % 4 != 0)
return 0;
$n = $n / 4;
}
return 1;
}
// Driver Code
1092
Chapter 172. Find whether a given number is a power of 4 or not
$test_no = 64;
if(isPowerOfFour($test_no))
echo $test_no," is a power of 4";
else
echo $test_no," is not a power of 4";
// This code is contributed by Rajesh
?>
Output :
64 is a power of 4
#include<stdio.h>
#define bool int
bool isPowerOfFour(unsigned int n)
{
int count = 0;
/*Check if there is only one bit set in n*/
if ( n && !(n&(n-1)) )
{
/* count 0 bits before set bit */
while(n > 1)
{
n >>= 1;
count += 1;
}
/*If count is even then return true else false*/
return (count%2 == 0)? 1 :0;
}
1093
Chapter 172. Find whether a given number is a power of 4 or not
Java
1094
Chapter 172. Find whether a given number is a power of 4 or not
Python3
1095
Chapter 172. Find whether a given number is a power of 4 or not
# Driver code
test_no = 64
if(isPowerOfFour(64)):
print(test_no, 'is a power of 4')
else:
print(test_no, 'is not a power of 4')
# This code is contribued by Danish Raza
C#
1096
Chapter 172. Find whether a given number is a power of 4 or not
if(isPowerOfFour(test_no)>0)
Console.WriteLine("{0} is a power of 4",
test_no);
else
Console.WriteLine("{0} is not a power of 4",
test_no);
}
}
// This Code is Contributed by mits
PHP
<?php
function isPowerOfFour($n)
{
$count = 0;
/*Check if there is only one bit set in n*/
if ( $n && !($n&($n-1)) )
{
/* count 0 bits before set bit */
while($n > 1)
{
$n >>= 1;
$count += 1;
}
/*If count is even then return true else false*/
return ($count%2 == 0)? 1 :0;
}
/* If there are more than 1 bit set
then n is not a power of 4*/
return 0;
}
/*Driver program to test above function*/
$test_no = 64;
if(isPowerOfFour($test_no))
echo $test_no, " is a power of 4";
else
1097
Chapter 172. Find whether a given number is a power of 4 or not
echo $test_no, " not is a power of 4";
#This Code is Contributed by Ajit
?>
Output:
64 is a power of 4
Source
https://www.geeksforgeeks.org/find-whether-a-given-number-is-a-power-of-4-or-not/
1098
Chapter 173
Input : N = 13
Output : Odd Parity
Bianry representation of 13 is (1101)
Input : N = 9 (1001)
Output : Even Parity
• y = x^(x>>1)
• y = y^(y>>2)
• y = y^(y>>4)
• y = y^(y>>8)
• y = y^(y>>16)
1099
Chapter 173. Finding the Parity of a number Efficiently
Now, the rightmost bit in y will represent the parity of x. If the rightmost bit is 1, then x
will have odd parity and if it is 0 then x will have even parity.
So, in order to extract the last bit of y, perform bit-wise AND operation of y with 1.
if(y&1==1)
odd Parity
else
even Parity
C++
1100
Chapter 173. Finding the Parity of a number Efficiently
Java
Python3
# Program to find the
# parity of a given number
1101
Chapter 173. Finding the Parity of a number Efficiently
1102
Chapter 173. Finding the Parity of a number Efficiently
PHP
<?php
// Program to find the
// parity of a given number
// Function to find the parity
function findParity($x)
{
$y = $x ^ ($x >> 1);
$y = $y ^ ($y >> 2);
$y = $y ^ ($y >> 4);
$y = $y ^ ($y >> 8);
$y = $y ^ ($y >> 16);
// Rightmost bit of y holds
// the parity value if (y&1)
// is 1 then parity is odd
// else even
if ($y & 1)
return 1;
return 0;
}
1103
Chapter 173. Finding the Parity of a number Efficiently
// Driver code
(findParity(9) == 0) ?
print("Even Parity\n"):
print("Odd Parity\n");
(findParity(13) == 0) ?
print("Even Parity\n"):
print("Odd Parity\n");
// This Code is Contributed by mits
?>
Output:
Even Parity
Odd Parity
Source
https://www.geeksforgeeks.org/finding-the-parity-of-a-number-efficiently/
1104
Chapter 174
First element greater than or equal to X in prefix sum of N numbers using Binary Lifting -
GeeksforGeeks
Given an array of N integers and a number X. The task is to find the index of first element
which is greater than or equal to X in prefix sums of N numbers.
Examples:
Approach: The problem can be solved using lower_bound function in Binary search. But
in this post, the problem will be solved using Binary-Lifting. In binary lifting, a value is
increased (or lifted) by powers of 2, starting with the highest possible power of 2(log(N))
down to the lowest power(0).
• initialize position = 0 and set each bit of position, from most significant bit to least
significant bit.
• whenever a bit is set to 1, the value of position increases (or lifts).
• while increasing or lifting position, make sure that prefix sum till position should be
less than v.
• here, log(N) bits are needed for all possible values of ‘position’ ( from log(N)th to
0th bit ).
1105
Chapter 174. First element greater than or equal to X in prefix sum of N numbers using
Binary Lifting
• determine the value of the i-th bit. First, check if setting the i-th bit won’t make
‘position’ greater than N, which is the size of the array. Before lifting to the new
‘position’, check that value at that new ‘position’ is less than X or not.
• if this condition is true, then target position lies above the ‘position’ + 2^i, but below
the ‘position’ + 2^(i+1). This is because if target position was above ‘position’ +
2^(i+1), then the position would have been already lifted by 2^(i+1) (this logic is
similar to binary lifting in trees).
• if it is false, then target value lies between ‘position’ and ‘position’ + 2^i, so try
to lift by a lower power of 2. Finally loop will end such that value at that position is
less than X. Here, in this question, the lower bound is asked. so, return ‘position’ +
1.
1106
Chapter 174. First element greater than or equal to X in prefix sum of N numbers using
Binary Lifting
Output:
Source
https://www.geeksforgeeks.org/first-element-greater-than-or-equal-to-x-in-prefix-sum-of-n-numbers-using-binary-li
1107
Chapter 175
Input: 2 5
Output: 7
2 is represented as 10 in binary and 5
is represented as 101. Hence toggling the
2nd bit of 5 from right, thus the new
number becomes 7 i.e. 111
Input: 1 3
Output: 2
Approach:
Just do XOR of the given two Number.
CPP
1108
Chapter 175. For every set bit of a number toggle bits of other
Java
Python3
1109
Chapter 175. For every set bit of a number toggle bits of other
# bits of n1.
# function for the Nega_bit
def toggleBits(n1, n2) :
return (n1 ^ n2)
# Driver program to test above
n1 = 2
n2 = 5
print(toggleBits(n1, n2))
# This code is contributed
# by Nikita Tiwari.
C#
PHP
<?php
1110
Chapter 175. For every set bit of a number toggle bits of other
Output :
Source
https://www.geeksforgeeks.org/for-every-set-bit-of-a-number-toggle-bits-of-other/
1111
Chapter 176
Input : N = 3.
Output : Player A
Player A remove stone 1 which is at the top, then Player B remove stone 2
and finally player A removes the last stone.
Input : N = 15.
Output : Player A
For N = 1, player A will remove the only stone from the pile and wins the game.
For N = 2, player A will remove the first stone and then player B remove the second or the
last stone. So player B will win the game.
So, we can observe player A wins when N is odd and player B wins when N is even.
Below is the implementation of this approach:
C++
1112
Chapter 176. Game of Nim with removal of one stone allowed
Java
1113
Chapter 176. Game of Nim with removal of one stone allowed
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
1114
Chapter 176. Game of Nim with removal of one stone allowed
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program for Game of
// Nim with removal of one
// stone allowed.
// Return true if player A wins,
// return false if player B wins.
function findWinner($N)
{
// Checking the last bit of N.
return $N&1;
}
// Driver Code
$N = 15;
if(findWinner($N))
echo "Player A";
else
echo "Player B";
// This code is contributed by vt_m.
?>
Output :
Player A
Source
https://www.geeksforgeeks.org/game-nim-removal-one-stone-allowed/
1115
Chapter 177
1116
Chapter 177. Generate 0 and 1 with 25% and 75% probability
PHP
<?php
// Program to print 1 with 75% probability
// and 0 with 25% probability
// Random Function to that returns 0 or
// 1 with equal probability
function rand50()
{
// rand() function will generate
// odd or even number with equal
// probability. If rand() generates
// odd number, the function will
// return 1 else it will return 0.
return rand() & 1;
}
// Random Function to that returns
// 1 with 75% probability and 0
// with 25% probability using
// Bitwise OR
function rand75()
{
return rand50() | rand50();
}
// Driver Code
1117
Chapter 177. Generate 0 and 1 with 25% and 75% probability
Output:
11101111110010010110011111111101111110111100011000
On similar lines, we can also use Bitwise AND. Since it returns 0 with 75% probability,
we have to invert the result.
We can replace Bitwise OR and Bitwise AND operator by OR and AND operators as
well –
We can also achieve the result using left shift operator and Bitwise XOR –
C++
1118
Chapter 177. Generate 0 and 1 with 25% and 75% probability
#include <iostream>
using namespace std;
// Random Function to that returns 0 or 1 with
// equal probability
int rand50()
{
// rand() function will generate odd or even
// number with equal probability. If rand()
// generates odd number, the function will
// return 1 else it will return 0.
return rand() & 1;
}
// Random Function to that returns 1 with 75%
// probability and 0 with 25% probability using
// left shift and Bitwise XOR
int rand75()
{
// x is one of {0, 1}
int x = rand50();
x = x << 1;
// x is now one of {00, 10}
x = x ^ rand50();
// x is now one of {00, 01, 10, 11}
return (x > 0) ? 1 : 0;
}
// Driver code to test above functions
int main()
{
// Intialize random number generator
srand(time(NULL));
for (int i = 0; i < 50; i++)
cout << rand75();
return 0;
}
PHP
<?php
1119
Chapter 177. Generate 0 and 1 with 25% and 75% probability
1120
Chapter 177. Generate 0 and 1 with 25% and 75% probability
Output:
01101110111011000111111111110001111011101110110110
Please note above solutions will produce different results every time we run them.
Improved By : jit_t
Source
https://www.geeksforgeeks.org/generate-0-1-25-75-probability/
1121
Chapter 178
The above sequences are Gray Codes of different widths. Following is an interesting pattern
in Gray Codes.
n-bit Gray Codes can be generated from list of (n-1)-bit Gray codes using fol-
lowing steps.
1) Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1.
2) Modify the list L1 by prefixing a ‘0’ in all codes of L1.
3) Modify the list L2 by prefixing a ‘1’ in all codes of L2.
4) Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes.
For example, following are steps for generating the 3-bit Gray code list from the list of 2-bit
Gray code list.
L1 = {00, 01, 11, 10} (List of 2-bit Gray Codes)
L2 = {10, 11, 01, 00} (Reverse of L1)
Prefix all entries of L1 with ‘0’, L1 becomes {000, 001, 011, 010}
Prefix all entries of L2 with ‘1’, L2 becomes {110, 111, 101, 100}
Concatenate L1 and L2, we get {000, 001, 011, 010, 110, 111, 101, 100}
1122
Chapter 178. Generate n-bit Gray Codes
To generate n-bit Gray codes, we start from list of 1 bit Gray codes. The list of 1 bit Gray
code is {0, 1}. We repeat above steps to generate 2 bit Gray codes from 1 bit Gray codes,
then 3-bit Gray codes from 2-bit Gray codes till the number of bits becomes equal to n.
Following is C++ implementation of this approach.
1123
Chapter 178. Generate n-bit Gray Codes
}
// Driver program to test above function
int main()
{
generateGrayarr(4);
return 0;
}
Output
000
001
011
010
110
111
101
100
This article is compiled by Ravi Chandra Enaganti. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/given-a-number-n-generate-bit-patterns-from-0-to-2n-1-so-that-successive-patterns
1124
Chapter 179
Input : n=2
Output :00 01 11 10
Input :n=3
Output :000 001 011 010 110 111 101 100
Another approach of Generate n-bit Gray Codes has been already discussed.
Approach is to get gray code of binary number using XOR and Right shift operation.
The first bit(MSB) of the gray code is same as the first bit(MSB) of binary number.
The second bit(from left side) of the gray code equals to XOR of first bit(MSB) and second
bit(2nd MSB) of the binary number.
The third bit(from left side) of the gray code equals to XOR of the second bit(2nd MSB)
and third bit(3rd MSB) and so on..
In this way we can get the gray code of corresponding binary number. So, observation is
that to get i’th bit gray code, we have to do XOR operation of i’th bit and previous i-1’th
bit. So by doing right shift, i-1’th bit and i’th bit come at same position and the XOR result
of i’th bit and i-1’th bit will be the i’th bit gray code.That’s the intuition behind right shift
operation.
C++
1125
Chapter 179. Generate n-bit Gray Codes | Set 2
1126
Chapter 179. Generate n-bit Gray Codes | Set 2
Java
1127
Chapter 179. Generate n-bit Gray Codes | Set 2
System.out.println();
}
}
// Driver code
public static void main (String[] args)
{
int n = 3;
generateGrayarr(n);
}
}
// This code is contributed
// by anuj_67.
C#
// C# program to generate
// n-bit gray codes
using System;
class GFG
{
// Function to convert
// decimal to binary
static void decimalToBinaryNumber(int x,
int n)
{
int []binaryNumber = new int[x];
int i = 0;
while (x > 0)
{
binaryNumber[i] = x % 2;
x = x / 2;
i++;
}
// leftmost digits are
// filled with 0
for (int j = 0; j < n - i; j++)
Console.Write('0');
for (int j = i - 1;
j >= 0; j--)
Console.Write(binaryNumber[j]);
}
1128
Chapter 179. Generate n-bit Gray Codes | Set 2
// Function to generate
// gray code
static void generateGrayarr(int n)
{
int N = 1 << n;
for (int i = 0; i < N; i++)
{
// generate gray code of
// corresponding binary
// number of integer i.
int x = i ^ (i >> 1);
// printing gray code
decimalToBinaryNumber(x, n);
Console.WriteLine();
}
}
// Driver code
public static void Main ()
{
int n = 3;
generateGrayarr(n);
}
}
// This code is contributed
// by anuj_67.
Output:
000
001
011
010
110
111
101
100
Improved By : vt_m
1129
Chapter 179. Generate n-bit Gray Codes | Set 2
Source
https://www.geeksforgeeks.org/generate-n-bit-gray-codes-set-2/
1130
Chapter 180
Input : n = 9
Output : 2
(9)10 = (1001)2
The position of rightmost unset bit in the binary
representation of 9 is 2.
Input : n = 32
Output : 1
1. If n = 0, return 1.
2. If all bits of n are set, return -1. Refer this post.
3. Else perform bitwise not on the given number(operation equivalent to 1’s complement).
Let it be num = ~n.
4. Get the position of rightmost set bit of num. This will be the position of rightmost
unset bit of n.
C++
1131
Chapter 180. Get the position of rightmost unset bit
Java
1132
Chapter 180. Get the position of rightmost unset bit
}
// function to get the position
// of rightmost unset bit
static int getPosOfRightMostUnsetBit(int n) {
// if n = 0, return 1
if (n == 0)
return 1;
// if all bits of 'n' are set
if ((n & (n + 1)) == 0)
return -1;
// position of rightmost unset bit in 'n'
// passing ~n as argument
return getPosOfRightmostSetBit(~n);
}
// Driver code
public static void main(String arg[])
{
int n = 9;
System.out.print(getPosOfRightMostUnsetBit(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
1133
Chapter 180. Get the position of rightmost unset bit
if (n == 0):
return 1
# if all bits of 'n' are set
if ((n & (n + 1)) == 0):
return -1
# position of rightmost unset bit in 'n'
# passing ~n as argument
return getPosOfRightmostSetBit(~n)
# Driver program to test above
n = 13;
ans = getPosOfRightMostUnsetBit(n)
#rounding the final answer
print (round(ans))
# This code is contributed by Saloni Gupta.
C#
1134
Chapter 180. Get the position of rightmost unset bit
PHP
<?php
// PHP implementation to get the
// position of rightmost unset bit
// function to find the position
// of rightmost set bit
function getPosOfRightmostSetBit( $n)
{
return ceil(log($n &- $n) + 1);
}
// function to get the position
// of rightmost unset bit
function getPosOfRightMostUnsetBit( $n)
{
// if n = 0, return 1
if ($n == 0)
return 1;
// if all bits of 'n' are set
if (($n & ($n + 1)) == 0)
return -1;
// position of rightmost unset bit in 'n'
// passing ~n as argument
return getPosOfRightmostSetBit(~$n);
}
// Driver Code
$n = 9;
echo getPosOfRightMostUnsetBit($n);
1135
Chapter 180. Get the position of rightmost unset bit
// This code is contributed by anuj_67.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/get-position-rightmost-unset-bit/
1136
Chapter 181
C++
1137
Chapter 181. Given a set, find XOR of the XOR’s of all subsets.
{
int Set[] = {1, 2, 3};
int n = sizeof(Set)/sizeof(Set[0]);
cout << "XOR of XOR's of all subsets is "
<< findXOR(Set, n);
return 0;
}
Java
Python3
1138
Chapter 181. Given a set, find XOR of the XOR’s of all subsets.
C#
1139
Chapter 181. Given a set, find XOR of the XOR’s of all subsets.
// This code is contributed by nitin mittal
PHP
<?php
// PHP program to find XOR
// of XOR's of all subsets
// Returns XOR of all
// XOR's of given subset
function findXOR($Set, $n)
{
// XOR is 1 only when
// n is 1, else 0
if ($n == 1)
return $Set[0];
else
return 0;
}
// Driver Code
$Set = array(1, 2, 3);
$n = count($Set);
echo "XOR of XOR's of all subsets is "
, findXOR($Set, $n);
// This code is contributed by anuj_67.
?>
Output:
Related Problem :
Sum of XOR of all possible subsets
How does this work?
The logic goes simple. Let us consider n’th element, it can be included in all subsets of
remaining (n-1) elements. The number of subsets for (n-1) elements is equal to 2(n-1) which
is always even when n>1. Thus, in the XOR result, every element is included even number
of times and XOR of even occurrences of any number is 0.
This article is contributed by Ekta Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, vt_m
1140
Chapter 181. Given a set, find XOR of the XOR’s of all subsets.
Source
https://www.geeksforgeeks.org/given-a-set-find-xor-of-the-xors-of-all-subsets/
1141
Chapter 182
n-bit Gray Codes can be generated from list of (n-1)-bit Gray codes using following steps.
Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1.
Modify the list L1 by prefixing a ‘0’ in all codes of L1.
Modify the list L2 by prefixing a ‘1’ in all codes of L2.
Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes.
Please refer Generate n-bit Gray Codesfor detailed program.
How to Convert Binary To Gray and Vice Versa?
1142
Chapter 182. Gray to Binary and Binary to Gray conversion
Binary : 0011
Gray : 0010
Binary : 01001
Gray : 01101
In computer science many a times we need to convert binary code to gray code and vice
versa. This conversion can be done by applying following rules :
Binary to Gray conversion :
1. The Most Significant Bit (MSB) of the gray code is always equal to the MSB of the
given binary code.
2. Other bits of the output gray code can be obtained by XORing binary code bit at that
index and previous index.
1. The Most Significant Bit (MSB) of the binary code is always equal to the MSB of the
given binary number.
2. Other bits of the output binary code can be obtained by checking gray code bit at
that index. If current gray code bit is 0, then copy previous binary code bit, else copy
invert of previous binary code bit.
C++
1143
Chapter 182. Gray to Binary and Binary to Gray conversion
gray += binary[0];
// Compute remaining bits, next bit is comuted by
// doing XOR of previous and current in Binary
for (int i = 1; i < binary.length(); i++) {
// Concatenate XOR of previous bit
// with current bit
gray += xor_c(binary[i - 1], binary[i]);
}
return gray;
}
// function to convert gray code string
// to binary string
string graytoBinary(string gray)
{
string binary = "";
// MSB of binary code is same as gray code
binary += gray[0];
// Compute remaining bits
for (int i = 1; i < gray.length(); i++) {
// If current bit is 0, concatenate
// previous bit
if (gray[i] == '0')
binary += binary[i - 1];
// Else, concatenate invert of
// previous bit
else
binary += flip(binary[i - 1]);
}
return binary;
}
// Driver program to test above functions
int main()
{
string binary = "01001";
cout << "Gray code of " << binary << " is "
<< binarytoGray(binary) << endl;
string gray = "01101";
cout << "Binary code of " << gray << " is "
<< graytoBinary(gray) << endl;
1144
Chapter 182. Gray to Binary and Binary to Gray conversion
return 0;
}
Java
1145
Chapter 182. Gray to Binary and Binary to Gray conversion
C#
1146
Chapter 182. Gray to Binary and Binary to Gray conversion
{
return (a == b) ? '0' : '1';
}
// Helper function to flip the bit
static char flip(char c)
{
return (c == '0') ? '1' : '0';
}
// function to convert binary
// string to gray string
static String binarytoGray(String binary)
{
String gray = "";
// MSB of gray code is same
// as binary code
gray += binary[0];
// Compute remaining bits, next
// bit is comuted by doing XOR
// of previous and current in
// Binary
for (int i = 1; i < binary.Length; i++)
{
// Concatenate XOR of previous
// bit with current bit
gray += xor_c(binary[i - 1],
binary[i]);
}
return gray;
}
// function to convert gray code
// string to binary string
static String graytoBinary(String gray)
{
String binary = "";
// MSB of binary code is same
// as gray code
binary += gray[0];
// Compute remaining bits
1147
Chapter 182. Gray to Binary and Binary to Gray conversion
Output:
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal
1148
Chapter 182. Gray to Binary and Binary to Gray conversion
Source
https://www.geeksforgeeks.org/gray-to-binary-and-binary-to-gray-conversion/
1149
Chapter 183
Input : n = 10
Output : 8
Input : n = 19
Output : 16
Input : n = 32
Output : 32
A simple solution is to start checking from n and keep decrementing until we find a power
of 2.
C++
1150
Chapter 183. Highest power of 2 less than or equal to given number
Java
1151
Chapter 183. Highest power of 2 less than or equal to given number
C#
PHP
<?php
// PHP program to find highest
// power of 2 smaller than or
// equal to n.
function highestPowerof2($n)
{
$res = 0;
for ($i = $n; $i >= 1; $i--)
{
1152
Chapter 183. Highest power of 2 less than or equal to given number
// If i is a power of 2
if (($i & ($i - 1)) == 0)
{
$res = $i;
break;
}
}
return $res;
}
// Driver code
$n = 10;
echo highestPowerof2($n);
// This code is contributed by m_kit
?>
Output :
Time complexity : O(n). In worst case, the loop runs floor(n/2) times. The worst case
happens when n is of the form 2x – 1.
An efficient solution is to use bitwise left shift operator to find all powers of 2 starting
from 1. For every power check if it is smaller than or equal to n or not. Below is C++
implementation of the idea.
C++
1153
Chapter 183. Highest power of 2 less than or equal to given number
Java
1154
Chapter 183. Highest power of 2 less than or equal to given number
res = curr;
}
return res;
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println(highestPowerof2(n));
}
}
// This code is contributed aj_36
C#
// C# program to find
// highest power of 2 smaller
// than or equal to n.
using System;
class GFG
{
static int highestPowerof2(int n)
{
// Invalid input
if (n < 1)
return 0;
int res = 1;
// Try all powers
// starting from 2^1
for (int i = 0; i < 8 ; i++)
{
int curr = 1 << i;
// If current power is
// more than n, break
if (curr > n)
break;
res = curr;
}
return res;
1155
Chapter 183. Highest power of 2 less than or equal to given number
}
// Driver code
static public void Main ()
{
int n = 10;
Console.WriteLine(highestPowerof2(n));
}
}
// This code is contributed ajit
PHP
<?php
// PHP program to find highest
// power of 2 smaller
// than or equal to n.
function highestPowerof2($n)
{
// Invalid input
if ($n < 1)
return 0;
$res = 1;
// Try all powers starting
// from 2^1
for ($i = 0; $i < 8 ; $i++)
{
$curr = 1 << $i;
// If current power is
// more than n, break
if ($curr > $n)
break;
$res = $curr;
}
return $res;
}
// Driver code
$n = 10;
echo highestPowerof2($n);
1156
Chapter 183. Highest power of 2 less than or equal to given number
Output :
Java
1157
Chapter 183. Highest power of 2 less than or equal to given number
}
// Driver code
public static void main (String[] args)
{
int n = 10;
System.out.println(highestPowerof2(n));
}
}
// This code is contributed
// by m_kit
C#
// C# program to find
// highest power of 2
// smaller than or equal to n.
using System;
class GFG
{
static int highestPowerof2(int n)
{
int p = (int)(Math.Log(n) /
Math.Log(2));
return (int)Math.Pow(2, p);
}
// Driver code
static public void Main ()
{
int n = 10;
Console.WriteLine(highestPowerof2(n));
}
}
// This code is contributed
// by ajit
PHP
<?php
// PHP program to find highest
// power of 2 smaller than or
// equal to n.
function highestPowerof2($n)
1158
Chapter 183. Highest power of 2 less than or equal to given number
{
$p = (int)log($n, 2);
return (int)pow(2, $p);
}
// Driver code
$n = 10;
echo highestPowerof2($n);
// This code is contributed by ajit
?>
Output :
Application Problem:
Some people are standing in a queue. A selection process follows a rule where people
standing on even positions are selected. Of the selected people a queue is formed and again
out of these only people on even position are selected. This continues until we are left with
one person. Find out the position of that person in the original queue.
Print the position(original queue) of that person who is left.
Examples :
Input: n = 10
Output:8
Explanation :
1 2 3 4 5 6 7 8 9 10 ===>Given queue
2 4 6 8 10
4 8
8
Input: n = 17
Input: 16
Explanation :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ===>Given queue
2 4 6 8 10 12 14 16
4 8 12 16
8 16
16
Related Article :
Power of 2 greater than or equal to a given number.
Improved By : jit_t
1159
Chapter 183. Highest power of 2 less than or equal to given number
Source
https://www.geeksforgeeks.org/highest-power-2-less-equal-given-number/
1160
Chapter 184
Input: n = 28, p1 = 0, p2 = 3
Output: 21
28 in binary is 11100. If we swap 0'th and 3rd digits,
we get 10101 which is 21 in decimal.
Input: n = 20, p1 = 2, p2 = 3
Output: 24
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to first find the bits, then use XOR based swapping concept, i..e., to swap two
numbers ‘x’ and ‘y’, we do x = x ^ y, y = y ^ x and x = x ^ y.
Below is C implementation.
1161
Chapter 184. How to swap two bits in a given integer?
Output:
Result = 21
Improved By : jit_t
Source
https://www.geeksforgeeks.org/how-to-swap-two-bits-in-a-given-integer/
1162
Chapter 185
1163
Chapter 185. How to swap two numbers without using a temporary variable?
1164
Chapter 185. How to swap two numbers without using a temporary variable?
#include <stdio.h>
int main()
{
int x = 10, y = 5;
// Code to swap 'x' and 'y'
x = x + y; // x now becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5
printf("After Swapping: x = %d, y = %d", x, y);
return 0;
}
Java
Python 3
x = 10
1165
Chapter 185. How to swap two numbers without using a temporary variable?
y = 5
# Code to swap 'x' and 'y'
# x now becomes 15
x = x + y
# y becomes 10
y = x - y
# x becomes 5
x = x - y
print("After Swapping: x =",x ," y =", y);
# This code is contributed
# by Sumit Sudhakar
C#
PHP
<?php
// PHP Program to swap two
// numbers without using
1166
Chapter 185. How to swap two numbers without using a temporary variable?
// temporary variable
$x = 10; $y = 5;
// Code to swap 'x' and 'y'
$x = $x + $y; // x now becomes 15
$y = $x - $y; // y becomes 10
$x = $x - $y; // x becomes 5
echo "After Swapping: x = ",
$x, "," , "y = ", $y;
// This code is contributed by m_kit
?>
Output :
After Swapping: x = 5, y = 10
#include <stdio.h>
int main()
{
int x = 10, y = 5;
// Code to swap 'x' and 'y'
x = x * y; // x now becomes 50
y = x / y; // y becomes 10
x = x / y; // x becomes 5
printf("After Swapping: x = %d, y = %d", x, y);
return 0;
}
Java
1167
Chapter 185. How to swap two numbers without using a temporary variable?
int x = 10;
int y = 5;
// Code to swap 'x' and 'y'
x = x * y; // x now becomes 50
y = x / y; // y becomes 10
x = x / y; // x becomes 5
System.out.println("After swaping:" +
" x = " + x +
", y = " + y);
}
}
// This code is contributed by ajit
Python3
C#
1168
Chapter 185. How to swap two numbers without using a temporary variable?
// temporary variable
using System;
class GFG
{
static public void Main ()
{
int x = 10;
int y = 5;
// Code to swap 'x' and 'y'
x = x * y; // x now becomes 50
y = x / y; // y becomes 10
x = x / y; // x becomes 5
Console.WriteLine("After swaping:" +
" x = " + x +
", y = " + y);
}
}
// This code is contributed by ajit.
PHP
<?php
// Driver code
$x = 10;
$y = 5;
// Code to swap 'x' and 'y'
$x = $x * $y; // x now becomes 50
$y = $x / $y; // y becomes 10
$x = $x / $y; // x becomes 5
echo "After Swapping: x = ", $x,
" ", "y = ", $y;
// This code is contributed by m_kit
?>
Output :
After Swapping: x = 5, y = 10
1169
Chapter 185. How to swap two numbers without using a temporary variable?
x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For
example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111)
and 5 (0101) is (0010).
C
#include <stdio.h>
int main()
{
int x = 10, y = 5;
// Code to swap 'x' (1010) and 'y' (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
printf("After Swapping: x = %d, y = %d", x, y);
return 0;
}
Java
import java.*;
public class GFG {
public static void main(String a[]){
int x = 10;
int y = 5;
// Code to swap 'x' (1010) and 'y' (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
System.out.println("After swap: x = "
+ x + ", y = " + y);
}
}
// This code is contributed by Sam007.
Python3
1170
Chapter 185. How to swap two numbers without using a temporary variable?
x = 10
y = 5
# Code to swap 'x' and 'y'
x = x ^ y; # x now becomes 15 (1111)
y = x ^ y; # y becomes 10 (1010)
x = x ^ y; # x becomes 5 (0101)
print ("After Swapping: x = ",x ," y =", y)
# This code is contributed by
# Sumit Sudhakar
C#
PHP
<?php
1171
Chapter 185. How to swap two numbers without using a temporary variable?
// Driver Code
$x = 10;
$y = 5;
// Code to swap 'x' (1010)
// and 'y' (0101)
// x now becomes 15 (1111)
$x = $x ^ $y;
// y becomes 10 (1010)
$y = $x ^ $y;
// x becomes 5 (0101)
$x = $x ^ $y;
echo "After Swapping: x = ", $x,
",", "y = ", $y;
// This code is contributed by aj_36
?>
Output :
After Swapping: x = 5, y = 10
1172
Chapter 185. How to swap two numbers without using a temporary variable?
#include <stdio.h>
void swap(int *xp, int *yp)
{
*xp = *xp ^ *yp;
*yp = *xp ^ *yp;
*xp = *xp ^ *yp;
}
int main()
{
int x = 10;
swap(&x, &x);
printf("After swap(&x, &x): x = %d", x);
return 0;
}
Output :
Swapping a variable with itself may needed in many standard algorithms. For example
see thisimplementation of QuickSortwhere we may swap a variable with itself. The above
problem can be avoided by putting a condition before the swapping.
C
#include <stdio.h>
void swap(int *xp, int *yp)
{
if (xp == yp) // Check if the two addresses are same
return;
*xp = *xp + *yp;
*yp = *xp - *yp;
*xp = *xp - *yp;
}
int main()
{
int x = 10;
swap(&x, &x);
printf("After swap(&x, &x): x = %d", x);
return 0;
}
Output :
Improved By : jit_t
1173
Chapter 185. How to swap two numbers without using a temporary variable?
Source
https://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/
1174
Chapter 186
Input: n = 15, k = 1
Output: 14
Input: n = 15, k = 2
Output: 13
Input: n = 15, k = 3
Output: 11
Input: n = 15, k = 4
Output: 7
The idea is to use bitwise <<, & and ~ operators. Using expression ”~(1 << (k – 1))“, we
get a number which has all bits set, except the k’th bit. If we do bitwise & of this expression
with n, we get a number which has all bits same as n except the k’th bit which is 0.
Below is the implementation of above idea.
C++
1175
Chapter 186. How to turn off a particular bit in a number?
#include <iostream>
using namespace std;
// Returns a number that has all bits same as n
// except the k'th bit which is made 0
int turnOffK(int n, int k)
{
// k must be greater than 0
if (k <= 0) return n;
// Do & of n with a number with all set bits except
// the k'th bit
return (n & ~(1 << (k - 1)));
}
// Driver program to test above function
int main()
{
int n = 15;
int k = 4;
cout << turnOffK(n, k);
return 0;
}
Java
1176
Chapter 186. How to turn off a particular bit in a number?
int k = 4;
System.out.println(turnOffK(n, k));
}
}
// Contributed by Pramod Kumar
Python3
C#
1177
Chapter 186. How to turn off a particular bit in a number?
{
// k must be greater than 0
if (k <= 0)
return n;
// Do & of n with a number
// with all set bits except
// the k'th bit
return (n & ~ (1 << (k - 1)));
}
// Driver Code
public static void Main ()
{
int n = 15;
int k = 4;
Console.Write(turnOffK(n, k));
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to turn off a
// particular bit in a number
// Returns a number that has
// all bits same as n except
// the k'th bit which is made 0
function turnOffK($n, $k)
{
// k must be greater than 0
if ($k <= 0)
return $n;
// Do & of n with a number
// with all set bits except
// the k'th bit
return ($n & ~(1 << ($k - 1)));
}
// Driver Code
$n = 15;
$k = 4;
echo turnOffK($n, $k);
1178
Chapter 186. How to turn off a particular bit in a number?
// This code is contributed by nitin mittal
?>
Output:
Exercise: Write a function turnOnK() that turns the k’th bit on.
This article is contributed by Rahul Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/how-to-turn-off-a-particular-bit-in-a-number/
1179
Chapter 187
Input: n = 4, k = 2
Output: 6
Input: n = 3, k = 3
Output: 7
Input: n = 64, k = 4
Output: 72
Input: n = 64, k = 5
Output: 80
The idea is to use bitwise << and | operators. Using expression ”(1 << (k – 1))“, we get
a number which has all bits unset, except the k’th bit. If we do bitwise | of this expression
with n, we get a number which has all bits same as n except the k’th bit which is 1.
Below is the implementation of above idea.
C++
1180
Chapter 187. How to turn on a particular bit in a number?
Java
1181
Chapter 187. How to turn on a particular bit in a number?
int n = 4;
int k = 2;
System.out.print(turnOnK(n, k));
}
}
// This code is contributed by Smitha
Python 3
C#
1182
Chapter 187. How to turn on a particular bit in a number?
PHP
<?php
// PHP program to turn on a particular bit
// Returns a number that has
// all bits same as n except
// the k'th bit which is made 1
function turnOnK($n, $k)
{
// k must be greater than 0
if ($k <= 0)
return $n;
// Do | of n with a number with all
// unset bits except the k'th bit
return ($n | (1 << ($k - 1)));
}
// Driver Code
$n = 4;
$k = 2;
1183
Chapter 187. How to turn on a particular bit in a number?
Output:
Source
https://www.geeksforgeeks.org/turn-particular-bit-number-2/
1184
Chapter 188
Input : 3
Output : 4
Input : 9
Output : 10
The idea is based on the fact that the negative numbers are stored using 2’s complement
form. 2’s complement form is obtained by inverting bits and then adding one. So if we
invert all bits of given number and apply negative sign, we get the number plus 1.
C++
1185
Chapter 188. Increment a number without using ++ or +
return i;
}
// Driver code
int main()
{
int n = 3;
cout << increment(n);
return 0;
}
Java
Python3
1186
Chapter 188. Increment a number without using ++ or +
C#
// C# program to increment
// an unsigned int using
// bitwise operators.
using System;
class GFG
{
// function that increment
// the value.
static long increment(long i)
{
// Invert bits and
// apply negative sign
i = -(~i);
return i;
}
// Driver code
public static void Main ()
{
long n = 3;
Console.WriteLine(increment(n));
}
}
// This code is contributed
1187
Chapter 188. Increment a number without using ++ or +
// by inder_verma.
PHP
<?php
// PHP program to increment
// an unsigned int using
// bitwise operators.
// function that increment the value.
function increment($i)
{
// Invert bits and
// apply negative sign
$i = -(~$i);
return $i;
}
// Driver code
$n = 3;
echo increment($n);
// This code is contributed by mits
?>
Output:
Input : a
Output : b
Input : o
Output : p
C++
1188
Chapter 188. Increment a number without using ++ or +
Java
Python3
1189
Chapter 188. Increment a number without using ++ or +
C#
// C# program to increment
// an unsigned char using
// bitwise operators.
class GFG
{
// function that increment the value.
static char increment(char i)
{
// Invert bits and apply
// negative sign
int i1 = -(~(int)(i));
return (char)(i1);
}
// Driver code
static void Main()
{
char n = ‘a’;
System.Console.WriteLine(increment(n));
}
}
// This code is contributed by mits
PHP
<?php
// PHP program to increment
1190
Chapter 188. Increment a number without using ++ or +
Output:
Source
https://www.geeksforgeeks.org/increment-a-number-without-using-or/
1191
Chapter 189
Input : 6
Output : 7
Input : 15
Output : 16
C++
1192
Chapter 189. Increment a number by one by manipulating the bits
1193
Chapter 189. Increment a number by one by manipulating the bits
Java
1194
Chapter 189. Increment a number by one by manipulating the bits
return n;
}
// Driver Program
public static void main (String[] args)
{
int n = 15;
System.out.println(incrementByOne(n));
}
}
// This code is contributed by Gitanjali.
Python 3
# python 3 implementation
# to increment a number
# by one by manipulating
# the bits
import math
# function to find the
# position of rightmost
# set bit
def getPosOfRightmostSetBit(n) :
return math.log2(n & -n)
# function to toggle the last m bits
def toggleLastKBits(n, k) :
# calculating a number
# 'num' having 'm' bits
# and all are set
num = (1 << (int)(k)) - 1
# toggle the last m bits and
# return the number
return (n ^ num)
# function to increment
# a number by one by
# manipulating the bits
def incrementByOne(n) :
# get position of rightmost
1195
Chapter 189. Increment a number by one by manipulating the bits
C#
1196
Chapter 189. Increment a number by one by manipulating the bits
PHP
<?php
1197
Chapter 189. Increment a number by one by manipulating the bits
1198
Chapter 189. Increment a number by one by manipulating the bits
echo incrementByOne($n);
// This code is contributed by Mithun Kumar
?>
Output :
16
Source
https://www.geeksforgeeks.org/increment-number-one-manipulating-bits/
1199
Chapter 190
Inserting M into N such that m starts at bit j and ends at bit i | Set-2 - GeeksforGeeks
Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to
insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits
j through i have enough space to fit all of M. Assuming index start from 0.
Examples:
a) N = 1024 (10000000000),
M = 19 (10011),
i = 2, j = 6
Output : 1100 (10001001100)
b) N = 1201 (10010110001)
M = 8 (1000)
i = 3, j = 6
Output: 1217 (10011000001)
This problem has been already discussed in the previous post. In this post, a different
approach is discussed.
Approach: The idea is very straightforward, following is the stepwise procedure –
1200
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
capture_mask = ( 1 << i ) - 1
capture_mask = ( 1 << 3 ) - 1
Now capture_mask = 1(001)
Now AND this mask with N, i-1 to 0 bits will remain same while rest bits become 0. Thus
we are left with i-1 to 0 bits only.
clear_mask = -1 << ( j + 1 )
N &= clear_mask
N &= clear_mask
Now N = 1152 (10010000000)
1201
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Inserting M in N
Now because N has bits from j to 0 cleared, just fit in M into N and shift M i position to
left to align the MSB of M with position j in N.
M <<= i
For example b-
M <<= 3
Now M = 8 << 3 = 64 (1000000)
N |= M
For example b –
N |= M
Now N = 1152 | 64 = 1216 (10011000000)
N |= captured_bits
For example b –
N |= captured_bits
N = 1216 | 1 = 1217 (10011000001)
1202
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
1203
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Java
1204
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
C#
1205
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
// C# program to insert
// 32-bit number M into N
// using bit magic
using System;
class GFG
{
// print binary
// representation of n
static void bin(long n)
{
if (n > 1)
bin(n / 2);
Console.Write(n % 2);
}
// Insert m into n
static int insertion(int n, int m,
int i, int j)
{
int clear_mask = -1 << (j + 1);
int capture_mask = (1 << i) - 1;
// Capturing bits from i-1 to 0
int captured_bits = n & capture_mask;
// Clearing bits from j to 0
n &= clear_mask;
// Shiftng m to align with n
m = m << i;
// Insert m into n
n |= m;
// Insert captured bits
n |= captured_bits;
return n;
}
// Driver Code
static public void Main (String []args)
{
// print original bitset
int N = 1201, M = 8, i = 3, j = 6;
Console.Write("N = " + N + "(");
1206
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
bin(N);
Console.WriteLine(")");
// print original bitset
Console.Write("M = " + M + "(");
bin(M);
Console.WriteLine(")");
// Call function to
// insert M to N
N = insertion(N, M, i, j);
Console.WriteLine("After inserting M " +
"into N from 3 to 6");
// Print the inserted bitset
Console.Write("N = " + N + "(");
bin(N);
Console.WriteLine(")");
}
}
// This code is contributed
// by Arnab Kundu
Python
1207
Chapter 190. Inserting M into N such that m starts at bit j and ends at bit i | Set-2
n |= captured_bits
return n
# Driver
def main():
N = 1201; M = 8; i = 3; j = 6
print("N = {}({})".format(N, bin(N)))
print("M = {}({})".format(M, bin(M)))
N = insertion(N, M, i, j)
print("***After inserting M into N***")
print("N = {}({})".format(N, bin(N)))
if __name__ == '__main__':
main()
Output:
N = 1201(10010110001)
M = 8(1000)
After inserting M into N from 3 to 6
N = 1217(10011000001)
Source
https://www.geeksforgeeks.org/inserting-m-into-n-such-that-m-starts-at-bit-j-and-ends-at-bit-i-set-2/
1208
Chapter 191
Inserting m into n such that m starts at bit j and ends at bit i. - GeeksforGeeks
We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n
starting from j to i. We can assume that the bits j through i have enough space to fit all
of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i.
You would not, for example, have j = 3 and i = 2, because m could not fully fit between
bit 3 and bit 2.
Examples :
Input : n = 1024
m = 19
i = 2
j = 6;
Output : n = 1100
Binary representations of input numbers
m in binary is (10011)2
n in binary is (10000000000)2
Binary representations of output number
(10000000000)2
Input : n = 5
m = 3
i = 1
j = 2
Output : 7
Algorithm :
1209
Chapter 191. Inserting m into n such that m starts at bit j and ends at bit i.
The trickiest part is Step 1. How do we clear the bits in n? We can do this with a mask.
This mask will have all 1s, except for 0s in the bits j through i. We create this mask by
creating the left half of the mask first, and then the right half.
Following is the implementation of the above approach.
C++
1210
Chapter 191. Inserting m into n such that m starts at bit j and ends at bit i.
Java
1211
Chapter 191. Inserting m into n such that m starts at bit j and ends at bit i.
Python3
1212
Chapter 191. Inserting m into n such that m starts at bit j and ends at bit i.
i = 2; j = 6
print(updateBits(n, m, i, j))
# This code is contributed by Anant Agarwal.
C#
1213
Chapter 191. Inserting m into n such that m starts at bit j and ends at bit i.
PHP
<?php
// PHP program for implementation
// of updateBits()
// Function to updateBits
// M insert to N.
function updateBits($n, $m, $i, $j)
{
// Create a mask to clear
// bits i through j in n.
// EXAMPLE: i = 2, j = 4.
// Result should be 11100011.
// For simplicity, we'll use
// just 8 bits for the example.
// will equal sequence of all ls
$allOnes = ~0;
// ls before position j, then
// 0s. left = 11100000
$left= $allOnes << ($j + 1);
// l's after position i.
// right = 00000011
$right = ((1 << $i) - 1);
1214
Chapter 191. Inserting m into n such that m starts at bit j and ends at bit i.
// All ls, except for 0s between
// i and j. mask 11100011
$mask = $left | $right;
// Clear bits j through i
// then put min there
// Clear bits j through i.
$n_cleared = $n & $mask;
// Move m into correct position.
$m_shifted = $m << $i;
// OR them, and we're done!
return ($n_cleared | $m_shifted);
}
// Driver Code
// in Binary N= 10000000000
$n = 1024;
// in Binary M= 10011
$m = 19;
$i = 2;
$j = 6;
echo updateBits($n, $m, $i, $j);
// This code is contributed by Ajit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/insertion-m-n-m-starts-bit-j-ends-bit/
1215
Chapter 192
Input : 11
Output : 4
(11)10 = (1011)[2]
After inverting the bits, we get:
(0100)2 = (4)10.
Input : 10
Output : 5
(10)10 = (1010)2.
After reversing the bits we get:
(0101)2 = (101)2
= (5)10.
C++
1216
Chapter 192. Invert actual bits of a number
Java
1217
Chapter 192. Invert actual bits of a number
invertBits(num);
}
}
// This code is contributed
// by Anuj_67
C#
// C# program to invert
// actual bits of a number.
using System;
class GFG
{
static void invertBits(int num)
{
// calculating number of
// bits in the number
int x = (int)(Math.Log(num) /
Math.Log(2)) + 1;
// Inverting the
// bits one by one
for (int i = 0; i < x; i++)
num = (num ^ (1 << i));
Console.WriteLine(num);
}
// Driver code
public static void Main ()
{
int num = 11;
invertBits(num);
}
}
// This code is contributed
// by Anuj_67
PHP
<?php
// PHP program to invert actual bits
1218
Chapter 192. Invert actual bits of a number
// of a number.
function invertBits( $num)
{
// calculating number of bits
// in the number
$x = log($num) + 1;
// Inverting the bits one by one
for($i = 0; $i < $x; $i++)
$num = ($num ^ (1 << $i));
echo $num;
}
// Driver code
$num = 11;
invertBits($num);
// This code is contributed by anuj_67.
?>
Output:
1219
Chapter 192. Invert actual bits of a number
int x = log2(num) + 1;
// Considering number to be 32 bit integer;
bitset<32> b(num);
// reversing the bits one by one
for (int i = 0; i < x; i++)
b.flip(i);
// converting bitset to number
cout << b.to_ulong();
}
// Driver code
int main()
{
int num = 11;
invertBits(num);
return 0;
}
C#
1220
Chapter 192. Invert actual bits of a number
}
}
// This code is contributed by Anuj_67
Output :
Source
https://www.geeksforgeeks.org/invert-actual-bits-number/
1221
Chapter 193
1222
Chapter 193. Josephus Problem Using Bit Magic
Now for every n the right position for Josephus can be found out by deducting the biggest
possible power of 2 from the number and we get the answer (provided that value of n is not
a pure power of 2 otherwise the answer is 1)
N = 2a + something
Where, a = biggest possible power
The Trick
Whenever someone talks about the powers of 2 the first word that comes to mind is “binary”.
The solution to this problem is much is easier and shorter in binary than in decimal. There
is a trick to this. Since we need to deduct the biggest possible power of in binary that
number is the Most Significant Bit. In the original Josephus problem there were 40 other
soldiers along with Josephus which makes n = 41. 41 in binary is 101001. If we shift the
MSB i.e. the leftmost 1 to the rightmost place we get 010011 which is 19 (in decimal) which
is the answer. This is true for all cases. This can be done easily using bit manipulation.
C
1223
Chapter 193. Josephus Problem Using Bit Magic
Java
1224
Chapter 193. Josephus Problem Using Bit Magic
1225
Chapter 193. Josephus Problem Using Bit Magic
Python3
1226
Chapter 193. Josephus Problem Using Bit Magic
C#
1227
Chapter 193. Josephus Problem Using Bit Magic
Output:
19
References:
1. Numberphile
2. Wikipedia
Improved By : vt_m
1228
Chapter 193. Josephus Problem Using Bit Magic
Source
https://www.geeksforgeeks.org/josephus-problem-using-bit-magic/
1229
Chapter 194
After the first person (kth from begining) is killed, n-1 persons are left. So we call josephus(n
– 1, k) to get the position with n-1 persons. But the position returned by josephus(n – 1,
k) will consider the position starting from k%n + 1. So, we must make adjustments to the
position returned by josephus(n – 1, k).
1230
Chapter 194. Josephus problem | Set 1 (A O(n) Solution)
#include <stdio.h>
int josephus(int n, int k)
{
if (n == 1)
return 1;
else
/* The position returned by josephus(n - 1, k) is adjusted because the
recursive call josephus(n - 1, k) considers the original position
k%n + 1 as position 1 */
return (josephus(n - 1, k) + k-1) % n + 1;
}
// Driver Program to test above function
int main()
{
int n = 14;
int k = 2;
printf("The chosen place is %d", josephus(n, k));
return 0;
}
Java
1231
Chapter 194. Josephus problem | Set 1 (A O(n) Solution)
Python3
C#
1232
Chapter 194. Josephus problem | Set 1 (A O(n) Solution)
{
if (n == 1)
return 1;
else
/* The position returned
by josephus(n - 1, k) is
adjusted because the
recursive call josephus(n
- 1, k) considers the
original position k%n + 1
as position 1 */
return (josephus(n - 1, k)
+ k-1) % n + 1;
}
// Driver Program to test above
// function
public static void Main()
{
int n = 14;
int k = 2;
Console.WriteLine("The chosen "
+ "place is " + josephus(n, k));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP code for
// Josephus Problem
function josephus($n, $k)
{
if ($n == 1)
return 1;
else
/* The position returned by
josephus(n - 1, k) is
adjusted because the
recursive call josephus
(n - 1, k) considers the
original position k%n + 1
as position 1 */
return (josephus($n - 1, $k) +
$k - 1) % $n + 1;
1233
Chapter 194. Josephus problem | Set 1 (A O(n) Solution)
}
// Driver Code
$n = 14;
$k = 2;
echo "The chosen place is ", josephus($n, $k);
// This code is contributed by ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/josephus-problem-set-1-a-on-solution/
1234
Chapter 195
Largest number with binary representation is m 1’s and m-1 0’s - GeeksforGeeks
Given n, find the greatest number which is strictly not more then n and whose binary
representation consists of m consecutive ones, then m-1 consecutive zeros and nothing else
Examples:
Input : n = 7
Output : 6
Explanation: 6's binary representation is 110,
and 7's is 111, so 6 consists of 2 consecutive
1's and then 1 consecutive 0.
Input : 130
Output : 120
Explanation: 28 and 120 are the only numbers <=120,
28 is 11100 consists of 3 consecutive 1's and then
2 consecutive 0's. 120 is 1111000 consists of 4
consecutive 1's and then 3 consecutive 0's. So 120
is the greatest of number<=120 which meets the
given condition.
A naive approach will be to traverse from 1 to N and check for every binary representation
which consists of m consecutive 1’s and m-1 consecutive 0’s and store the largest of them
which meets the given condition.
An efficient approach is to observe a pattern of numbers,
1235
Chapter 195. Largest number with binary representation is m 1’s and m-1 0’s
We can iterate till the number does not exceeds N and print the largest of all possible
elements. A closer observation will shows that at m = 33 it will exceed the 10^18
mark , so we are calculating the number in unit’s time as log(32) is near to constant
which is required in calculating the pow .
So, the overall complexity will be O(1).
C++
1236
Chapter 195. Largest number with binary representation is m 1’s and m-1 0’s
ans = r;
// increment m to get the next number
m++;
}
return ans;
}
// driver code to check the above condition
int main()
{
long long n = 7;
cout << answer(n);
return 0;
}
Java
1237
Chapter 195. Largest number with binary representation is m 1’s and m-1 0’s
Python3
1238
Chapter 195. Largest number with binary representation is m 1’s and m-1 0’s
if r < n:
ans = r;
# increment m to get
# the next number
m = m + 1;
return ans;
# Driver Code
print(answer(7));
# This code is contributed by mits.
C#
1239
Chapter 195. Largest number with binary representation is m 1’s and m-1 0’s
m++;
}
return ans;
}
// Driver Code
static public void Main ()
{
long n = 7;
Console.WriteLine(answer(n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find largest number
// smaller than equal to n with m set
// bits then m-1 0 bits.
// Returns largest number with m set
// bits then m-1 0 bits.
function answer( $n)
{
// Start with 2 bits.
$m = 2;
// initial answer is 1
// which meets the
// given condition
$ans = 1;
$r = 1;
// check for all numbers
while ($r < $n)
{
// compute the number
$r = (pow(2, $m) - 1) *
(pow(2, $m - 1));
// if less then N
if ($r < $n)
$ans = $r;
1240
Chapter 195. Largest number with binary representation is m 1’s and m-1 0’s
// increment m to get
// the next number
$m++;
}
return $ans;
}
// Driver Code
$n = 7;
echo answer($n);
// This code is contributed by Ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/largest-number-binary-representation-m-1s-m-1-0s/
1241
Chapter 196
Input : n = 5
Output : arr[] = [0, 1, 4, 5]
The bitwise OR of 0, 1, 4 and 5 equals 5.
It is not possible to obtain a set larger than this.
Input : n = 8
Output : arr[] = [0, 8]
1242
Chapter 196. Largest set with bitwise OR equal to n
Algorithm:
Traverse the numbers from 0 to n, checking its bitwise OR with n. If the bitwise OR equals
n, then include that number in the resulting set.
Output:
0 1 4 5
Source
https://www.geeksforgeeks.org/largest-set-bitwise-equal-n/
1243
Chapter 197
Output:
a<<1 = 10
b<<1 = 18
>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second
operand decides the number of places to shift.
1244
Chapter 197. Left Shift and Right Shift Operators in C/C++
Output:
a>>1 = 2
b>>1 = 4
Important Points :
• The left shift and right shift operators should not be used for negative numbers. The
result of is undefined behaviour if any of the operands is a negative number. For
example results of both -1 << 1 and 1 << -1 is undefined.
• If the number is shifted more than the size of integer, the behaviour is undefined. For
example, 1 << 33 is undefined if integers are stored using 32 bits. See this for more
details.
• The left-shift by 1 and right-shift by 1 are equivalent to multiplication and division
by 2 respectively.
As mentioned in point 1, it works only if numbers are positive.
#include<stdio.h>
int main()
{
int x = 19;
printf ("x << 1 = %d\n", x << 1);
printf ("x >> 1 = %d\n", x >> 1);
return 0;
}
Output:
1245
Chapter 197. Left Shift and Right Shift Operators in C/C++
x << 1 = 38
x >> 1 = 9
#include<stdio.h>
int main()
{
int i = 3;
printf("pow(2, %d) = %d\n", i, 1 << i);
i = 4;
printf("pow(2, %d) = %d\n", i, 1 << i);
return 0;
}
Output:
pow(2, 3) = 8
pow(2, 4) = 16
Source
https://www.geeksforgeeks.org/left-shift-right-shift-operators-c-cpp/
1246
Chapter 198
Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on
adjacent pairs - GeeksforGeeks
Given an array of N(always a power of 2) elements and Q queries.
Every Query consists of two elements index and value.. We need to write a program that
assigns value to Aindex and prints the single element which is left after performing below
operations for each query:
• At alternate steps perform bitwise OR and bitwise XOR operations to the adjacent
elements.
• In first iteration select, select n/2 pairs moving from left to right, and do a bitwise
OR of all the pair values. In second iteration select (n/2)/2 leftover pairs and do a
bitwise XOR on them. In the third iteration select, select ((n/2)/2)/2 leftover pairs
moving from left to right, and do a bitwise OR of all the pair values.
• Continue the above steps till we are left with a single element.
Examples:
Input : n = 4 m = 2
arr = [1, 4, 5, 6]
Queries-
1st: index=0 value=2
1247
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
Explanation:
1st query:
2nd Query:
Naive Approach: The naive approach is to perform every step till we are leftover with
one element. Using 2-D vector we will store the resultant elements left after every step.
V[steps-1][0..size] gives the number of elements at previous step. If the step number is odd,
we perform a bitwise OR operation, else a bitwise XOR operation is done. Repeat the steps
till we are left over with one element. The last element left will be our answer.
Below is the implementation of the naive approach:
1248
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
int lastElement(int a[],int n)
{
// count the step number
int steps = 1;
vector<int>v[N];
// if one element is there, it will be the answer
if (n==1) return a[0];
// at first step we do a bitwise OR
for (int i = 0 ; i < n ; i += 2)
v[steps].push_back(a[i] | a[i+1]);
// keep on doing bitwise operations till the
// last element is left
while (v[steps].size()>1)
{
steps += 1;
// perform operations
for (int i = 0 ; i < v[steps-1].size(); i+=2)
{
// if step is the odd step
if (steps&1)
v[steps].push_back(v[steps-1][i] | v[steps-1][i+1]);
else // even step
v[steps].push_back(v[steps-1][i] ^ v[steps-1][i+1]);
}
}
// answer when one element is left
return v[steps][0];
}
// Driver Code
int main()
{
int a[] = {1, 4, 5, 6};
int n = sizeof(a)/sizeof(a[0]);
// 1st query
int index = 0;
int value = 2;
a[0] = 2;
1249
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
Output:
1
3
1250
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
.
The image above explains the construction of the tree if the sequence was [1, 2, 3, 4, 5, 6, 7,
8], then after 3 iterations, we will be left over with 12 which is our answer and is stored at
the root.
Answering Query
There is no need to rebuild the complete tree to perform an update operation. To do an
update, we should find a path from the root to the corresponding leaf and recalculate
the values only at the parents that are lying on the found path.
Level of parent:
Using DP on trees, we can easily store the level of every parent. Initialize the leaf nodes
level to 0, and keep adding as we move up to every parent.
The recurrence relation for calculating the level of parent is:
level[parent] = level[child] + 1
Here, child is 2*pos + 1 or 2*pos + 2
1251
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
C++
1252
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
1253
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
constructTree(0, n - 1, 0, a);
// 1st query
int index = 0;
int value = 2;
updateValue(index, value, a, n);
cout << tree[0] << endl;
// 2nd query
index = 3;
value = 5;
updateValue(index, value, a, n);
cout << tree[0] << endl;
return 0;
}
Java
1254
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
}
int mid = (low + high) / 2;
// recursive call
constructTree(low, mid, 2 * pos + 1, a);
constructTree(mid + 1, high,
2 * pos + 2, a);
// increase the level of every parent,
// which is level of child + 1
level[pos] = level[2 * pos + 1] + 1;
// if the parent is at odd level, then
// do a bitwise OR
if ((level[pos] & 1) > 0)
tree[pos] = tree[2 * pos + 1] |
tree[2 * pos + 2];
// if the parent is at even level, then
// do a bitwise XOR
else
tree[pos] = tree[2 * pos + 1] ^
tree[2 * pos + 2];
}
// fucntion that updates the tree
static void update(int low, int high, int pos,
int index, int []a)
{
// if it is a leaf and the leaf which is
// to be updated
if (low == high && low == index)
{
tree[pos] = a[low];
return;
}
// out of range
if (index < low || index > high)
return;
// not a leaf then recurse
if (low != high)
{
int mid = (low + high) / 2;
1255
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
1256
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
}
}
// This code is contributed by vt_m.
C#
1257
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
// if the parent is at odd level,
// then do a bitwise OR
if ((level[pos] & 1) > 0)
tree[pos] = tree[2 * pos + 1] |
tree[2 * pos + 2];
// if the parent is at even level,
// then do a bitwise XOR
else
tree[pos] = tree[2 * pos + 1] ^
tree[2 * pos + 2];
}
// fucntion that updates the tree
static void update(int low, int high,
int pos, int index, int []a)
{
// if it is a leaf and the leaf
// which is to be updated
if (low == high && low == index)
{
tree[pos] = a[low];
return;
}
// out of range
if (index < low || index > high)
return;
// not a leaf then recurse
if (low != high)
{
int mid = (low + high) / 2;
// recursive call
update(low, mid, 2 * pos + 1,
index, a);
update(mid + 1, high, 2 * pos + 2,
index, a);
// check if the parent is at odd
// or even level and perform OR
// or XOR according to that
if ((level[pos] & 1) > 0)
tree[pos] = tree[2 * pos + 1] |
1258
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
Output:
1
3
1259
Chapter 198. Leftover element after performing alternate Bitwise OR and Bitwise XOR
operations on adjacent pairs
Time Complexity:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/leftover-element-performing-alternate-bitwise-bitwise-xor-operations-adjacent-pairs
1260
Chapter 199
Input : n = 14
Output : 3
The binary representation of 14 is 1110.
Input : n = 222
Output : 4
The binary representation of 222 is 11011110.
Naive Approach: One simple way would be to simply loop over the bits, and keep track
of the number of consecutive set bits, and the maximum that this value has reached. In this
approach, we need to convert it to binary (base-2) representation and then find and print
the result.
Using Bit Magic: The idea is based on the concept that if we AND a bit sequence with
a shifted version of itself, we’re effectively removing the trailing 1 from every sequence of
consecutive 1s.
11101111 (x)
& 11011110 (x << 1)
----------
1261
Chapter 199. Length of the Longest Consecutive 1s in Binary Representation
So the operation x = (x & (x << 1)) reduces length of every sequence of 1s by one in
binary representation of x. If we keep doing this operation in a loop, we end up with x =
0. The number of iterations required to reach 0 is actually length of the longest consecutive
sequence of 1s.
C++
Java
1262
Chapter 199. Length of the Longest Consecutive 1s in Binary Representation
Python3
1263
Chapter 199. Length of the Longest Consecutive 1s in Binary Representation
C#
1264
Chapter 199. Length of the Longest Consecutive 1s in Binary Representation
// Driver code
public static void Main()
{
Console.WriteLine(maxConsecutiveOnes(14));
Console.Write(maxConsecutiveOnes(222));
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to find length
// of the longest consecutive
// 1s in binary reprsentation of
// a number.
function maxConsecutiveOnes($x)
{
// Initialize result
$count = 0;
// Count the number of
// iterations to reach x = 0.
while ($x != 0)
{
// This operation reduces
// length of every sequence
// of 1s by one.
$x = ($x & ($x << 1));
$count++;
}
return $count;
}
// Driver code
echo maxConsecutiveOnes(14), "\n";
echo maxConsecutiveOnes(222), "\n";
// This code is contributed by Ajit
?>
Output :
1265
Chapter 199. Length of the Longest Consecutive 1s in Binary Representation
3
4
Source
https://www.geeksforgeeks.org/length-longest-consecutive-1s-binary-representation/
1266
Chapter 200
1267
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
The operations (OR) and (XOR) indicate which operation was carried out to merge the
child node
Given 2N leaf nodes, the task is to build such a segment tree and print the root node
Examples:
This is a Extension to the Classical Segment Tree where we represent each node as as
integer and the parent node is built by first building the left and the right subtrees and
then combining the results of the left and the right children into the parent node. This
merging of the left and right children into the parent node is done by a consistent operations
For example, MIN()/MAX() in Range Minimum Queries, Sum, XOR, OR, AND, etc. By
consistent operations, we mean that this operation is performed to merge any node’s left
and right child into the parent node by carrying the operation say OP on their results, where
OP is a consistent operation.
In this Segment tree, we carry two operations that are -: OR and XOR.
Now we build the Segment tree in a similar fashion as we do in the classical version, but
now when we recursively pass the information for the sub-trees we will also pass information
regarding the operation to be carried out at that level since these operations alternate
levelwise. Its important to note that a parent node when calls its left and right children the
same operation information is passed to both the children as they are on the same level.
1268
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
Lets represent the two operations i.e OR and XOR by 0 and 1 respectively. Then if at Level
i we have an OR operation the at Level (i + 1) we will have an XOR operation. There if
Level i has 0 as operation then level (i + 1) will have 1 as operation
The parent child relationship for a segment tree node is shown in the below image:
If we carefully look at the image then it would be easy to figure out that if the height of the
tree is even then the root node is a result of XOR operation of its left and right children
else a result of OR operation.
1269
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
1270
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
Output:
1271
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of
every node is calculated only once in tree construction.
We can also perform Point Updates in a similar manner. If we get an update to update
the leaf at index i of the array leaves then we traverse down the tree to the leaf node and
perform the update. While coming back to the root node we build the tree again similar
to the build() function by passing the operation to be performed at every level and storing
the result of applying that operation on values of its left and right children and storing the
result into that node.
Consider the following Segment tree after performing the update,
Leaves[0] = 13
Now the updated segment tree looks like this:
Here the nodes in black denote the fact that they were updated
1272
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
1273
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
1274
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
1275
Chapter 200. Levelwise Alternating OR and XOR operations in Segment Tree
Output:
The time complexity of update is also O(Logn). To update a leaf value, we process one node
at every level and number of levels is O(Logn).
Improved By : sirjan13
Source
https://www.geeksforgeeks.org/levelwise-alternating-xor-operations-segment-tree/
1276
Chapter 201
Suppose integer is stored as 4 bytes (For those who are using DOS based compilers
such as C++ 3.0 , integer is 2 bytes) then a variable x with value 0x01234567 will be stored
as following.
#include <stdio.h>
1277
Chapter 201. Little and Big Endian Mystery
/* function to show bytes in memory, from location start to start+n*/
void show_mem_rep(char *start, int n)
{
int i;
for (i = 0; i < n; i++)
printf(" %.2x", start[i]);
printf("\n");
}
/*Main function to call above function for 0x01234567*/
int main()
{
int i = 0x01234567;
show_mem_rep((char *)&i, sizeof(i));
getchar();
return 0;
}
When above program is run on little endian machine, gives “67 45 23 01” as output , while
if it is run on endian machine, gives “01 23 45 67” as output.
Is there a quick way to determine endianness of your machine?
There are n no. of ways for determining endianness of your machine. Here is one quick way
of doing the same.
#include <stdio.h>
int main()
{
unsigned int i = 1;
char *c = (char*)&i;
if (*c)
printf("Little endian");
else
printf("Big endian");
getchar();
return 0;
}
1278
Chapter 201. Little and Big Endian Mystery
It matters in network programming: Suppose you write integers to file on a little endian
machine and you transfer this file to a big endian machine. Unless there is little endian to
big endian transformation, big endian machine will read the file in reverse order. You can
find such a practical example here.
Standard byte order for networks is big endian, also known as network byte order. Before
transferring data on network, data is first converted to network byte order (big endian).
Sometimes it matters when you are using type casting, below program is an example.
#include <stdio.h>
int main()
{
unsigned char arr[2] = {0x01, 0x00};
unsigned short int x = *(unsigned short int *) arr;
printf("%d", x);
getchar();
return 0;
}
In the above program, a char array is typecasted to an unsigned short integer type. When
I run above program on little endian machine, I get 1 as output, while if I run it on a big
endian machine I get 256. To make programs endianness independent, above programming
style should be avoided.
1279
Chapter 201. Little and Big Endian Mystery
Source
https://www.geeksforgeeks.org/little-and-big-endian-mystery/
1280
Chapter 202
Input : 5
Output : 3
Explanation :
N=5
Soldier 1 2 3 4 5 (5 soldiers)
In first go 1 3 5 (remains) as 2 and 4 killed by 1 and 3.
In second go 3 as 5 killed 1 and 3rd kill 5 soldier 3 remains alive.
Input : 100
Output : 73
Explanation :
N = 10
Soldiers 1 2 3 4 5 6 7 8 9 10 (10 soldiers)
In first 1 3 5 7 9 as 2 4 6 8 10 were killed by 1 3 5 7 and 9.
In second 1 5 9 as 9 kill 1 and in turn 5 kill 9th soldier.
In third 5 5th soldiers remain alive
Approach : The idea is to use circular linked list. A circular linked list is made based
on number of soldier N. As rule state you have to kill your adjacent soldier and handover
1281
Chapter 202. Lucky alive person in a circle | Code Solution to sword puzzle
the sword to the next soldier who in turn kill his adjacent soldier and handover sword to
the next soldier. So in circular linked list the adjacent soldier are killed and the remaining
soldier fights against each other in a circular way and a single soldier survive who is not
killed by anyone.
1282
Chapter 202. Lucky alive person in a circle | Code Solution to sword puzzle
temp = curr;
curr = curr->next;
temp->next = curr->next;
// deleting soldier from the circular
// list who is killed in the fight.
delete curr;
temp = temp->next;
curr = temp;
}
// Returning the Luckiest soldier who
// remains alive.
int res = temp->data;
delete temp;
return res;
}
// Driver code
int main()
{
int N = 100;
cout << alivesol(N) << endl;
return 0;
}
Output:
73
Source
https://www.geeksforgeeks.org/lucky-alive-person-circle/
1283
Chapter 203
Input : m = 4, k = 2
Output : 9
(9)10 = (1001)2, it is the 4th smallest
number having 2 set bits.
Input : m = 6, k = 4
Output : 39
1. Find the smallest number having k number of set bits. Let it be num, where num =
(1 << k) – 1.
2. Loop for m-1 times and each time replace num with the next higher number than
‘num’ having same number of bits as in ‘num’. Refer this post to find the required
next higher number.
3. Finally return num.
1284
Chapter 203. M-th smallest number having k number of set bits.
#include <bits/stdc++.h>
using namespace std;
typedef unsigned int uint_t;
// function to find the next higher number
// with same number of set bits as in 'x'
uint_t nxtHighWithNumOfSetBits(uint_t x)
{
uint_t rightOne;
uint_t nextHigherOneBit;
uint_t rightOnesPattern;
uint_t next = 0;
/* the approach is same as dicussed in
http://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/
*/
if (x) {
rightOne = x & -(signed)x;
nextHigherOneBit = x + rightOne;
rightOnesPattern = x ^ nextHigherOneBit;
rightOnesPattern = (rightOnesPattern) / rightOne;
rightOnesPattern >>= 2;
next = nextHigherOneBit | rightOnesPattern;
}
return next;
}
// function to find the mth smallest number
// having k number of set bits
int mthSmallestWithKSetBits(uint_t m, uint_t k)
{
// smallest number having 'k'
// number of set bits
uint_t num = (1 << k) - 1;
// finding the mth smallest number
// having k set bits
for (int i = 1; i < m; i++)
num = nxtHighWithNumOfSetBits(num);
1285
Chapter 203. M-th smallest number having k number of set bits.
Output:
39
Source
https://www.geeksforgeeks.org/m-th-smallest-number-k-number-set-bits/
1286
Chapter 204
Maximize a given unsigned number number by swapping bits at it’s extreme positions. -
GeeksforGeeks
Given a number maximize it by swapping bits at it’s extreme positions i.e. at first and last
position, second and second last position and so on.
Examples:
Input : 4 (0000...0100)
Output : 536870912 (0010...0000)
In the above example swapped 3rd and 3rd last
bit to maximize the given unsigned number.
Input : 12 (00000...1100)
Output : 805306368 (0011000...0000)
Naive Approach:
1. Convert the number into it’s bit representation and store it’s bit representation in an
array.
2. Traverse the array from both ends, if the less significant bit of the bit representation is
greater than the more significant bit i.e. if less significant bit is 1 and more significant bit
is 0 then swap them else take no action.
1287
Chapter 204. Maximize a given unsigned number number by swapping bits at it’s extreme
positions.
1288
Chapter 204. Maximize a given unsigned number number by swapping bits at it’s extreme
positions.
ull num = 4;
cout << findMax(num);
return 0;
}
Output:
536870912
Source
https://www.geeksforgeeks.org/maximize-given-unsigned-number-number-swapping-bits-extreme-positions/
1289
Chapter 205
1290
Chapter 205. Maximize the bitwise OR of an array
Java
1291
Chapter 205. Maximize the bitwise OR of an array
Python 3
1292
Chapter 205. Maximize the bitwise OR of an array
# Function to maximize the bitwise
# OR sum
def maxOR(arr, n, k, x):
preSum = [0] * (n + 1)
suffSum = [0] * (n + 1)
pow = 1
# Compute x^k
for i in range(0 ,k):
pow *= x
# Find prefix bitwise OR
preSum[0] = 0
for i in range(0, n):
preSum[i + 1] = preSum[i] | arr[i]
# Find suffix bitwise OR
suffSum[n] = 0
for i in range(n-1, -1, -1):
suffSum[i] = suffSum[i + 1] | arr[i]
# Find maximum OR value
res = 0
for i in range(0 ,n):
res = max(res, preSum[i] |
(arr[i] * pow) | suffSum[i + 1])
return res
# Drivers code
arr = [1, 2, 4, 8 ]
n = len(arr)
k = 2
x = 3
print(maxOR(arr, n, k, x))
# This code is contributed by Smitha
C#
1293
Chapter 205. Maximize the bitwise OR of an array
PHP
<?php
1294
Chapter 205. Maximize the bitwise OR of an array
Output :
1295
Chapter 205. Maximize the bitwise OR of an array
79
Source
https://www.geeksforgeeks.org/maximize-the-bitwise-or-of-an-array/
1296
Chapter 206
Input : 1 (0000....0001)
Output : 2147483648 (1000....0000)
Input : 7 (0000....0111)
Output : 3758096384 (0111....0000)
Method 1 (Simple)
1. Find binary representation of the number using simple decimal to binary representation
technique.
2. Count number of set bits in the binary representation equal to ‘n’.
3. Create a binary representation with its ‘n’ most significant bits set to 1.
4. Convert the binary representation back to the number.
C++
1297
Chapter 206. Maximize the number by rearranging bits
// Returns maximum number formed by
// bits of a given number.
ll maximize(ll a)
{
// _popcnt32(a) gives number of 1's
// present in binary representation of a.
ll n = _popcnt32(a);
// Set most significant n bits of res.
ll res = 0;
for (int i=1; i<=n; i++)
res |= (1 << (32 - i));
return res;
}
// Driver function.
int main()
{
ll a = 1;
cout << maximize(a) << endl;
return 0;
}
Java
1298
Chapter 206. Maximize the number by rearranging bits
return counter;
}
// Returns maximum number formed
// by bits of a given number.
static long maximize(long a)
{
// _popcnt32(a) gives number
// of 1's present in binary
// representation of a.
int n = _popcnt32(a);
// Set most significant
// n bits of res.
long res = 0;
for (int i = 1; i <= n; i++)
res = (int)res | (1 << (32 - i));
return Math.abs(res);
}
// Driver Code
public static void main(String args[])
{
long a = 1;
System.out.print(maximize(a));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
1299
Chapter 206. Maximize the number by rearranging bits
# Returns maximum number formed
# by bits of a given number.
def maximize(a) :
# _popcnt32(a) gives number
# of 1's present in binary
# representation of a.
n = _popcnt32(a)
# Set most significant
# n bits of res.
res = 0
for i in range(1, n + 1) :
res = int(res |
(1 << (32 - i)))
return abs(res)
# Driver Code
a = 1
print (maximize(a))
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
1300
Chapter 206. Maximize the number by rearranging bits
long res = 0;
for (int i = 1; i <= n; i++)
res = (int)res | (1 << (32 - i));
return Math.Abs(res);
}
// Driver Code.
static void Main()
{
long a = 1;
Console.WriteLine(maximize(a));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
// An simple PHP program to find
// minimum number formed by bits
// of a given number.
function _popcnt32($number)
{
$counter = 0;
while($number > 0)
{
if($number % 2 == 1)
{
$counter++;
}
//or number = number >> 1
$number = intval($number / 2);
}
return $counter;
}
// Returns maximum number formed
// by bits of a given number.
function maximize($a)
{
// _popcnt32(a) gives number
// of 1's present in binary
// representation of a.
$n = _popcnt32($a);
1301
Chapter 206. Maximize the number by rearranging bits
// Set most significant
// n bits of res.
$res = 0;
for ($i = 1; $i <= $n; $i++)
$res = intval($res |
(1 << (32 - $i)));
return abs($res);
}
// Driver Code
$a = 1;
echo (maximize($a));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
2147483648
Method 2 (Efficient)
The idea is to first find a number with n least significant set bits, then shift the number
left by 32-n.
C++
1302
Chapter 206. Maximize the number by rearranging bits
return a;
// find a number witn n least
// significant set bits.
ll res = (1 << n) - 1;
// Now shift result by 32 - n
return (res << (32 - n)) ;
}
// Driver function.
int main()
{
ll a = 3;
cout << maximize(a) << endl;
return 0;
}
Java
1303
Chapter 206. Maximize the number by rearranging bits
C#
1304
Chapter 206. Maximize the number by rearranging bits
PHP
<?php
// An efficient Java program to
// find minimum number formed
// by bits of a given number.
function _popcnt32($n)
{
$count = 0;
while ($n != 0)
{
$n = $n & ($n - 1);
$count++;
}
1305
Chapter 206. Maximize the number by rearranging bits
return $count;
}
// Returns maximum number
// formed by bits of a
// given number.
function maximize($a)
{
// _popcnt32(a) gives number
// of 1's present in binary
// representation of a.
$n = _popcnt32($a);
// If a$32
// bits are set.
if ($n == 32)
return $a;
// find a number witn
// n least significant
// set bits.
$res = (1 << $n) - 1;
// Now shift result
// by 32 - n
return ($res << (32 - $n)) ;
}
// Driver Code
$a = 3;
echo (maximize($a));
// This code is contributed by
// ManishShaw(manishshaw1)
?>
Output:
3221225472
Note: The above codes use GCC specific functions. If we wish to write code for other
compilers, we may use Count set bits in an integer.
Improved By : manishshaw1
1306
Chapter 206. Maximize the number by rearranging bits
Source
https://www.geeksforgeeks.org/maximize-number-rearranging-bits/
1307
Chapter 207
Input : n = 47
Output: 1
// binary of n = 47 is 101111
Input : n = 549
Output: 3
// binary of n = 549 is 1000100101
Input : n = 1030
Output: 7
// binary of n = 1030 is 10000000110
Input : n = 8
Output: -1
// There is only one 1 in binary representation
// of 8.
The idea to solve this problem is to use shift operator. We just need to find the position
of two immediate 1’s in binary representation of n and maximize the difference of these
position.
1308
Chapter 207. Maximum 0’s between two immediate 1’s in binary representation
• Return -1 if number is 0 or is a power of 2. In these cases there are less than two 1’s
in binary representation.
• Initialize variable prev with position of first right most 1, it basically stores the
position of previously seen 1.
• Now take another variable cur which stores the position of immediate 1 just after
prev.
• Now take difference of cur – prev – 1, it will be the number of 0’s between to
immediate 1’s and compare it with previous max value of 0’s and update prev i.e;
prev=cur for next iteration.
• Use auxiliary variable setBit, which scans all bits of n and helps to detect if current
bits is 0 or 1.
• Initially check if N is 0 or power of 2.
C++
1309
Chapter 207. Maximum 0’s between two immediate 1’s in binary representation
C#
1310
Chapter 207. Maximum 0’s between two immediate 1’s in binary representation
// loop to find position of right most 1
// here sizeof int is 4 that means total 32 bits
int setBit = 1, prev = 0, i;
for (i = 1; i <= sizeof(int) * 8; i++) {
prev++;
// we have found right most 1
if ((n & setBit) == setBit) {
setBit = setBit << 1;
break;
}
// left shift setBit by 1 to check next bit
setBit = setBit << 1;
}
// now loop through for remaining bits and find
// position of immediate 1 after prev
int max0 = int.MinValue, cur = prev;
for (int j = i + 1; j <= sizeof(int) * 8; j++) {
cur++;
// if cuurent bit is set, then compare
// difference of cur - prev -1 with
// previous maximum number of zeros
if ((n & setBit) == setBit) {
if (max0 < (cur - prev - 1))
max0 = cur - prev - 1;
// update prev
prev = cur;
}
setBit = setBit << 1;
}
return max0;
}
// Driver program to run the case
static public void Main()
{
int n = 549;
// Initially check that number must not
// be 0 and power of 2
Console.WriteLine(maxZeros(n));
}
}
1311
Chapter 207. Maximum 0’s between two immediate 1’s in binary representation
// This code is contributed by vt_m.
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-0s-two-immediate-1s-binary-representation/
1312
Chapter 208
Naive Approach : Basic Approach is same as maximum xor value. We iterate over all
the possible pair and calculate the AND value of those all. Pick the largest value among
them. Time complexity of this solution is O(n^2).
C++
1313
Chapter 208. Maximum AND value of a pair in an array
Java
1314
Chapter 208. Maximum AND value of a pair in an array
Python3
C#
1315
Chapter 208. Maximum AND value of a pair in an array
PHP
<?php
// PHP Program to find maximum
// XOR value of a pair
// Function for finding
// maximum and value pair
function maxAND($arr, $n)
{
$res = 0;
for ($i = 0; $i < $n; $i++)
for ($j = $i + 1; $j < $n; $j++)
$res = max($res, $arr[$i] &
$arr[$j]);
return $res;
}
// Driver Code
$arr = array(4, 8, 6, 2);
$n = count($arr);
echo "Maximum AND Value = " , maxAND($arr, $n);
// This code is contributed by vt_m.
?>
Output:
Better Approach : Idea is based on properties of AND operator. AND operation of any
two bits result in 1 iff both bits are 1. We start from the MSB and check whether we have
minimum of two elements of array having set value. If yes then that MSB will be part of
1316
Chapter 208. Maximum AND value of a pair in an array
our solution and be added to result otherwise we will discard that bit. Similary, iterating
from MSB to LSB (32 to 1) for bit position we can easily check which bit will be part of
our solution and will keep adding all such bits to our solution.
Explanation : Lets consider 1st example of {4, 8, 12, 16} :
C++
1317
Chapter 208. Maximum AND value of a pair in an array
Java
1318
Chapter 208. Maximum AND value of a pair in an array
Python3
1319
Chapter 208. Maximum AND value of a pair in an array
C#
1320
Chapter 208. Maximum AND value of a pair in an array
PHP
<?php
// PHP Program to find maximum
// XOR value of a pair
// Utility function to check
// number of elements having
// set msb as of pattern
function checkBit($pattern, $arr, $n)
{
$count = 0;
for ($i = 0; $i < $n; $i++)
if (($pattern & $arr[$i]) == $pattern)
$count++;
return $count;
}
// Function for finding
1321
Chapter 208. Maximum AND value of a pair in an array
Output:
Source
https://www.geeksforgeeks.org/maximum-value-pair-array/
1322
Chapter 209
Maximum OR sum of
sub-arrays of two different
arrays
Observe the operation of Bitwise OR operator. If we take two integers X and Y, then (X|Y
>= X). It can be proved by taking some examples. Lets derive a formula using the above
equation.
1323
Chapter 209. Maximum OR sum of sub-arrays of two different arrays
and also
So, we get maximum sum when we take the OR of the whole array ->
Below is the implementation of above approach:
C++
Java
1324
Chapter 209. Maximum OR sum of sub-arrays of two different arrays
{
int sum1 = 0, sum2 = 0;
// OR sum of all the elements
// in both arrays
for (int i = 0; i < n; i++) {
sum1 |= a[i];
sum2 |= b[i];
}
System.out.println(sum1 + sum2);
}
// Driver code
public static void main(String arg[])
{
int A[] = {1, 2, 4, 3, 2};
int B[] = {2, 3, 3, 12, 1};
int n = A.length;
MaximumSum(A, B, n);
}
}
// This code is contributed by Anant Agarwal.
Python3
1325
Chapter 209. Maximum OR sum of sub-arrays of two different arrays
MaximumSum(A, B, n)
# This code is contributed by Smitha Dinesh Semwal
C#
PHP
<?php
// PHP program to find maximum OR sum
// function to find maximum OR sum
function MaximumSum($a, $b, $n)
{
1326
Chapter 209. Maximum OR sum of sub-arrays of two different arrays
$sum1 = 0;
$sum2 = 0;
// OR sum of all the elements
// in both arrays
for ($i = 0; $i < $n; $i++)
{
$sum1 |= $a[$i];
$sum2 |= $b[$i];
}
echo ($sum1 + $sum2)."\n";
}
// Driver Code
$A = array(1, 2, 4, 3, 2 );
$B = array(2, 3, 3, 12, 1 );
$n = sizeof($A) / sizeof($A[0]);
MaximumSum($A, $B, $n);
// This code is contributed by mits
?>
Output :
22
Source
https://www.geeksforgeeks.org/maximum-sum-sub-arrays-two-different-arrays/
1327
Chapter 210
Input : n = 4, k = 3
Output : 7
Explanation
Maximum possible xor sum is 1 ^ 2 ^ 4 = 7.
Input : n = 11, k = 1
Output : 11
Explanation
Maximum Possible xor sum is 11.
If we have k = 1 then the maximum possible xor sum is 1. Now for k > 1 we can always
have an number with its all bits set to 1. So result will be maximum number greater than
n with its all bits set to 1.
C++
1328
Chapter 210. Maximum XOR using K numbers from 1 to n
Java
1329
Chapter 210. Maximum XOR using K numbers from 1 to n
Python
1330
Chapter 210. Maximum XOR using K numbers from 1 to n
k = 3
print( maxXorSum(n, k) )
# This code is contributed by Abhishek Sharma44.
C#
PHP
1331
Chapter 210. Maximum XOR using K numbers from 1 to n
<?php
// PHP program to find max xor sum
// of 1 to n using atmost k numbers
// To return max xor sum of 1 to n
// using at most k numbers
function maxXorSum($n, $k)
{
// If k is 1 then maximum
// possible sum is n
if ($k == 1)
return $n;
// Finding number greater than
// or equal to n with most
// significant bit same as n.
// For example, if n is 4, result
// is 7. If n is 5 or 6, result is 7
$res = 1;
while ($res <= $n)
$res <<= 1;
// Return res - 1 which denotes
// a number with all bits set to 1
return $res - 1;
}
// Driver code
$n = 4;
$k = 3;
echo maxXorSum($n, $k);
// This code is contributed by Mithun Kumar
?>
Output :
Source
https://www.geeksforgeeks.org/maximum-xor-using-k-numbers-1-n/
1332
Chapter 211
Input : L = 8
R = 20
Output : 31
31 is XOR of 15 and 16.
Input : L = 1
R = 3
Output : 3
A simple solution is to generate all pairs, find their XOR values and finally return the
maximum XOR value.
An efficient solution is to consider pattern of binary values from L to R. We can see that
first bit from L to R either changes from 0 to 1 or it stays 1 i.e. if we take the XOR of any
two numbers for maximum value their first bit will be fixed which will be same as first bit
of XOR of L and R itself.
After observing the technique to get first bit, we can see that if we XOR L and R, the most
significant bit of this XOR will tell us the maximum value we can achieve i.e. let XOR of L
and R is 1xxx where x can be 0 or 1 then maximum XOR value we can get is 1111 because
from L to R we have all possible combination of xxx and it is always possible to choose these
bits in such a way from two numbers such that their XOR becomes all 1. It is explained
below with some examples,
1333
Chapter 211. Maximum XOR value of a pair from a range
Examples 1:
L = 8 R = 20
L ^ R = (01000) ^ (10100) = (11100)
Now as L ^ R is of form (1xxxx) we
can get maximum XOR as (11111) by
choosing A and B as 15 and 16 (01111
and 10000)
Examples 2:
L = 16 R = 20
L ^ R = (10000) ^ (10100) = (00100)
Now as L ^ R is of form (1xx) we can
get maximum xor as (111) by choosing
A and B as 19 and 20 (10011 and 10100)
So the solution of this problem depends on the value of (L ^ R) only. We will calculate the
L^R value first and then from most significant bit of this value, we will add all 1s to get
the final result.
C++
1334
Chapter 211. Maximum XOR value of a pair from a range
maxXOR += two;
two <<= 1;
}
return maxXOR;
}
// Driver code to test above methods
int main()
{
int L = 8;
int R = 20;
cout << maxXORInRange(L, R) << endl;
return 0;
}
Java
1335
Chapter 211. Maximum XOR value of a pair from a range
}
// main function
public static void main (String[] args)
{
int L = 8;
int R = 20;
System.out.println(maxXORInRange(L, R));
}
}
Python3
1336
Chapter 211. Maximum XOR value of a pair from a range
C#
1337
Chapter 211. Maximum XOR value of a pair from a range
PHP
<?php
// PHP program to get maximum
// xor value of two numbers
// in a range
// method to get maximum xor
// value in range [L, R]
function maxXORInRange($L, $R)
{
// get xor of limits
$LXR = $L ^ $R;
// loop to get msb
// position of L^R
$msbPos = 0;
while ($LXR)
{
$msbPos++;
$LXR >>= 1;
}
// construct result by
// adding 1, msbPos times
$maxXOR = 0;
$two = 1;
while ($msbPos--)
{
$maxXOR += $two;
$two <<= 1;
}
return $maxXOR;
}
// Driver Code
$L = 8;
$R = 20;
echo maxXORInRange($L, $R), "\n";
// This code is contributed by aj_36
?>
Output :
31
1338
Chapter 211. Maximum XOR value of a pair from a range
Source
https://www.geeksforgeeks.org/maximum-xor-value-of-a-pair-from-a-range/
1339
Chapter 212
Maximum XOR-value of
at-most k-elements from 1 to n
Input : n = 7, k = 3
Output : 7
Explanation : You can select 1, 2, 4 for maximum XOR-value
Input : n = 7, k = 2
Output : 7
Explanation : You can select 3 and 4 for maximum value.
For any value of k we can select atleast two numbers from 1 to n and for the required result
we have to take a closer look on the bit-representation of n. So lets understand it through
an example. Suppose n = 6 and k = 2:
Bit representation of 6 = 110
Bit representation of 5 = 101
Bit representation of 4 = 100
Bit representation of 3 = 011
Bit representation of 2 = 010
Bit representation of 1 = 001
Now, you can see that after selecting as much numbers you want and selecting any of them
you can not obtain XOR value greater than 111 i.e 7. So, for a given n and k >1 the maxi-
mum possible XOR value is 2log2(n)+1 -1 (that is the value when all bits of n are turned to 1).
1340
Chapter 212. Maximum XOR-value of at-most k-elements from 1 to n
C++
Java
1341
Chapter 212. Maximum XOR-value of at-most k-elements from 1 to n
}
}
// This code is contributed by Smitha
Python3
C#
1342
Chapter 212. Maximum XOR-value of at-most k-elements from 1 to n
int k = 3;
Console.Write(maxXOR(n, k)) ;
}
}
// This code is contributed by Smitha
PHP
<?php
// Program to obtain maximum
// XOR value sub-array
// function to calculate
// maximum XOR value
function maxXOR($n, $k)
{
$c = log($n, 2) + 1;
// Return (2^c - 1)
return ((1 << $c) - 1);
}
// Driver Code
$n = 12;
$k = 3;
echo maxXOR($n, $k);
// This code is contributed by aj_36
?>
Output:
15
Source
https://www.geeksforgeeks.org/maximum-xor-value-k-elements-1-n/
1343
Chapter 213
Maximum set bit sum in array without considering adjacent elements - GeeksforGeeks
Given an array of integers arr[]. The task is to find the maximum sum of set bits(of the
array elements) without adding the set bits of adjacent elements of the array.
Examples:
1344
Chapter 213. Maximum set bit sum in array without considering adjacent elements
Approach:
1. First of all, find the total number of set bits for every element of the array and store
them in a different array or the same array(to avoid using extra space).
2. Now, the problem is reduced to find the maximum sum in the array such that no two
elements are adjacent.
3. Loop for all elements in arr[] and maintain two sums incl and excl where incl =
Max sum including the previous element and excl = Max sum excluding the previous
element.
4. Max sum excluding the current element will be max(incl, excl) and max sum including
the current element will be excl + current element (Note that only excl is considered
because elements cannot be adjacent).
5. At the end of the loop return max of incl and excl.
C++
#include<bits/stdc++.h>
using namespace std;
// Function to count total number
// of set bits in an integer
int bit(int n)
1345
Chapter 213. Maximum set bit sum in array without considering adjacent elements
{
int count = 0;
while(n)
{
count++;
n = n & (n - 1);
}
return count;
}
// Maximum sum of set bits
int maxSumOfBits(int arr[], int n)
{
// Calculate total number of
// set bits for every element
// of the array
for(int i = 0; i < n; i++)
{
// find total set bits for
// each number and store
// back into the array
arr[i] = bit(arr[i]);
}
int incl = arr[0];
int excl = 0;
int excl_new;
for (int i = 1; i < n; i++)
{
// current max excluding i
excl_new = (incl > excl) ?
incl : excl;
// current max including i
incl = excl + arr[i];
excl = excl_new;
}
// return max of incl and excl
return ((incl > excl) ?
incl : excl);
}
// Driver code
int main()
1346
Chapter 213. Maximum set bit sum in array without considering adjacent elements
{
int arr[] = {1, 2, 4, 5,
6, 7, 20, 25};
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxSumOfBits(arr, n);
return 0;
}
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Function to count total number
// of set bits in an integer
static int bit(int n)
{
int count = 0;
while(n > 0)
{
count++;
n = n & (n - 1);
}
return count;
}
// Maximum sum of set bits
static int maxSumOfBits(int arr[], int n)
{
// Calculate total number of set bits
// for every element of the array
for(int i = 0; i < n; i++)
{
// find total set bits for
// each number and store
// back into the array
arr[i] = bit(arr[i]);
}
int incl = arr[0];
1347
Chapter 213. Maximum set bit sum in array without considering adjacent elements
C#
using System;
class GFG
{
// Function to count total number
// of set bits in an integer
static int bit(int n)
{
int count = 0;
while(n > 0)
{
count++;
1348
Chapter 213. Maximum set bit sum in array without considering adjacent elements
n = n & (n – 1);
}
return count;
}
// Maximum sum of set bits
static int maxSumOfBits(int []arr, int n)
{
// Calculate total number of set bits
// for every element of the array
for(int i = 0; i < n; i++) { // find total set bits for // each number and store // back into
the array arr[i] = bit(arr[i]); } int incl = arr[0]; int excl = 0; int excl_new; for (int i = 1; i
< n; i++) { // current max excluding i excl_new = (incl > excl) ?
incl : excl;
// current max including i
incl = excl + arr[i];
excl = excl_new;
}
// return max of incl and excl
return ((incl > excl) ?
incl : excl);
}
// Driver code
public static void Main()
{
int []arr = {1, 2, 4, 5,
6, 7, 20, 25};
int n = arr.Length;
Console.WriteLine(maxSumOfBits(arr, n));
}
}
// This code is contributed
// by chandan_jnu.
Output:
1349
Chapter 213. Maximum set bit sum in array without considering adjacent elements
Source
https://www.geeksforgeeks.org/maximum-set-bit-sum-in-array-without-considering-adjacent-elements/
1350
Chapter 214
Input : X = 2
Output : 1
The only way of obtaining 2 is to directly transform 0 to 2 (bitwise AND of 0
and 2 is 0) and hence requires one step.
Input : X = 3
Output : 2
3 can be obtained in two steps. First, transform 0 to 1 (bitwise AND of 0 and 1
is 0). Then, transform 1 to 3 (bitwise AND of 1 and 3 is 1).
1351
Chapter 214. Maximum steps to transform 0 to X with bitwise AND
the right and a set bit can not be cleared once it set.
Example:
Suppose we want to obtain 13 (1101 in binary) from 0. We start by setting the 1st bit from
the right by transforming 0 to 1 (0001 in binary). We next set the 3rd bit from the right to
form 5 (0101 in binary). The last step would be to set the 4th bit and obtain 13 (1101).
C++
Java
1352
Chapter 214. Maximum steps to transform 0 to X with bitwise AND
{
count += n & 1;
n >>= 1;
}
return count;
}
// Driver code
public static void main(String[] args)
{
int i = 3;
System.out.print(countSetBits(i));
}
}
// This code is contributed by Smitha.
Python3
C#
1353
Chapter 214. Maximum steps to transform 0 to X with bitwise AND
// Function to get no. of
// set bits in binary
// representation of
// positive integer n
static int countSetBits(int n)
{
int count = 0;
while (n != 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
// Driver code
public static void Main(String[] args)
{
int i = 3;
Console.Write(countSetBits(i));
}
}
// This code is contributed by Smitha.
PHP
<?php
// PHP code to find the
// maximum possible effort
// Function to get no of
// set bits in binary
// representation of positive
// integer n
function countSetBits($n)
{
$count = 0;
while ($n)
{
$count += $n & 1;
$n >>= 1;
}
return $count;
}
// Driver code
1354
Chapter 214. Maximum steps to transform 0 to X with bitwise AND
$i = 3;
echo (countSetBits($i));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output :
Source
https://www.geeksforgeeks.org/maximum-steps-transform-0-x-bitwise/
1355
Chapter 215
Method 1(Simple):
The naive method would be to consider all the subsets. While considering a subset, compute
its bitwise OR. If it equals k, compare the subset’s length with the maximum length so far
and update the maximum length if required.
Method 2(Efficient):
0 OR 0 = 0
1 OR 0 = 1
1 OR 1 = 1
Hence, for all the positions in the binary representation of k with the bit equal to 0, the
1356
Chapter 215. Maximum subset with bitwise OR equal to k
corresponding position in the binary representations of all the elements in the resulting
subset should necessarily be 0.
On the other hand, for positions in k with the bit equal to 1, there has to be at least one
element with a 1 in the corresponding position. Rest of the elements can have either 0 or 1
in that position, it does not matter.
Therefore, to obtain the resulting subset, traverse the initial array. While deciding if the
element should be in the resulting subset or not, check whether there is any position in the
binary representation of k which is 0 and the corresponding position in that element is 1. If
there exists such a position, then ignore that element, else include it in the resulting subset.
How to determine if there exists a position in the binary representation of k which is 0 and
the corresponding position in an element is 1?
Simply take bitwise OR of k and that element. If it does not equal to k, then there exists
such a position and the element has to be ignored. If their bitwise OR equals to k, then
include the current element in the resulting subset.
The final step is to determine if there is at least one element with a 1 in a position with 1
in the corresponding position in k.
Simply compute the bitwise OR of the resulting subset. If it equals to k, then this is the
final answer. Else no subset exists which satisfies the condition.
C++
1357
Chapter 215. Maximum subset with bitwise OR equal to k
// If ans is not equal to k, subset doesn't exist
if (ans != k) {
cout << "Subset does not exist" << endl;
return;
}
for (int i = 0; i < v.size(); i++)
cout << v[i] << ' ';
}
// Driver Code
int main()
{
int k = 3;
int arr[] = { 1, 4, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
subsetBitwiseORk(arr, n, k);
return 0;
}
Java
1358
Chapter 215. Maximum subset with bitwise OR equal to k
// Store the bitwise OR of elements
// in v
int ans = 0;
for (int i = 0; i < v.size(); i++)
ans = ans|v.get(i);
// If ans is not equal to k, subset
// doesn't exist
if (ans != k) {
System.out.println("Subset does"
+ " not exist" );
return;
}
for (int i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " " );
}
// main function
public static void main(String[] args)
{
int k = 3;
int arr[] = { 1, 4, 2 };
int n = arr.length;
subsetBitwiseORk(arr, n, k);
}
}
// This code is contributed by Arnab Kundu.
Python3
1359
Chapter 215. Maximum subset with bitwise OR equal to k
C#
1360
Chapter 215. Maximum subset with bitwise OR equal to k
// If the bitwise OR of k and
// element is equal to k, then
// include that element in the
// subset
if ((arr[i] | k) == k){
v.Add(arr[i]);
}
}
// Store the bitwise OR of
// elements in v
int ans = 0;
for (int i = 0; i < v.Count; i++)
ans = ans|(int)v[i];
// If ans is not equal to k, subset
// doesn't exist
if (ans != k) {
Console.WriteLine("Subset does"
+ " not exist" );
return;
}
for (int i = 0; i < v.Count; i++)
Console.Write((int)v[i] + " " );
}
// main function
static public void Main(String []args)
{
int k = 3;
int []arr = { 1, 4, 2 };
int n = arr.Length;
subsetBitwiseORk(arr, n, k);
}
}
// This code is contributed by Arnab Kundu
PHP
<?php
// PHP Program to find the
// maximum subset with bitwise
1361
Chapter 215. Maximum subset with bitwise OR equal to k
// OR equal to k
// function to find the maximum
// subset with bitwise OR equal to k
function subsetBitwiseORk($arr, $n, $k)
{
$v = array();
for ($i = 0; $i < $n; $i++)
{
// If the bitwise OR of k
// and element is equal to k,
// then include that element
// in the subset
if (($arr[$i] | $k) == $k)
array_push($v, $arr[$i]);
}
// Store the bitwise OR
// of elements in v
$ans = 0;
for ($i = 0; $i < count($v); $i++)
$ans |= $v[$i];
// If ans is not equal to
// k, subset doesn't exist
if ($ans != $k)
{
echo ("Subset does not exist\n");
return;
}
for ($i = 0; $i < count($v); $i++)
echo ($v[$i]." ");
}
// Driver Code
$k = 3;
$arr = array(1, 4, 2);
$n = count($arr);
subsetBitwiseORk($arr, $n, $k);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
1362
Chapter 215. Maximum subset with bitwise OR equal to k
Output :
1 2
Source
https://www.geeksforgeeks.org/maximum-subset-bitwise-equal-k/
1363
Chapter 216
Maximum sum by adding numbers with same number of set bits - GeeksforGeeks
Given an array of N numbers, the task is to find the maximum sum that can be obtained
by adding numbers with the same number of set bits.
Examples:
Input: 32 3 7 5 27 28
Output: 34
Input: 2 3 8 5 6 7
Output: 14
1364
Chapter 216. Maximum sum by adding numbers with same number of set bits
Approach:
• Traverse in the array and count the number of set bits for every element.
• Initialize an array for 32 bits, assuming the number to have a maximum of 32 set bits.
• Iterate in the array and add the array element to the position which indicates the
number of set bits.
• Traverse and find the maximum sum and return it.
C++
1365
Chapter 216. Maximum sum by adding numbers with same number of set bits
1366
Chapter 216. Maximum sum by adding numbers with same number of set bits
Java
1367
Chapter 216. Maximum sum by adding numbers with same number of set bits
// Find the maximum sum
for (int i = 0; i < 32; i++)
{
maximum = Math.max(sum[i], maximum);
}
return maximum;
}
// Driver code
public static void main (String[] args)
{
int[] arr = { 2 ,3 , 8, 5, 6, 7 };
int n = arr.length;
System.out.println(maxsum(arr, n));
}
}
// This Code is contributed by mits
C#
1368
Chapter 216. Maximum sum by adding numbers with same number of set bits
}
// Function to return the
// the maximum sum
static int maxsum(int[] arr, int n)
{
int[] bits = new int[n];
// Calculate the
for (int i = 0; i < n; i++)
{
bits[i] = bit_count(arr[i]);
}
// Assuming the number to be
// a maximum of 32 bits
int[] sum = new int[32];
// Add the number to the
// number of set bits
for (int i = 0; i < n; i++)
{
sum[bits[i]] += arr[i];
}
int maximum = 0;
// Find the maximum sum
for (int i = 0; i < 32; i++)
{
maximum = Math.Max(sum[i], maximum);
}
return maximum;
}
// Driver code
static void Main()
{
int[] arr = { 2 ,3 , 8, 5, 6, 7 };
int n = arr.Length;
Console.WriteLine(maxsum(arr, n));
}
}
// This Code is contributed by mits
PHP
1369
Chapter 216. Maximum sum by adding numbers with same number of set bits
Output:
14
Source
https://www.geeksforgeeks.org/maximum-sum-by-adding-numbers-with-same-number-of-set-bits/
1370
Chapter 217
Input : arr[] = { 0, 0, 0, 1, 1, 0 }
x = 0, y = 5
Output : Anti-clockwise 0
The path 0 -> 1 -> 2 -> 3 -> 4 -> 5, we have only 1 value change i.e from index 2 to 3.
The path 0 -> 5 have 0 value change.
So, the answer is Anti-clockwise 0.
Input : s = { 1, 1, 0, 1, 1 }
x = 2, y = 0
Output : Clockwise 1
The idea is to check by going once Clockwise and store the count1 and then going anti-
clockwise and store the count2. Then output by comparing count1 and count2.
How to travel clockwise or anticlockwise?
It will be hard to travel clockwise in the array where x > y and same in case of anticlockwise
where y > x. So, we will store the given binary array in the string “S”. And to make it
circular, we will append S to S i.e S = S + S. We will make the adjustment in x and y to
travel clockwise or anticlockwise.
1371
Chapter 217. Minimum bit changes in Binary Circular array to reach a index
Now, if y > x and to go clockwise, it will be easy to iterate from x to y and calculate the
number of flip bits.
If y > x and to go anti-clockwise, we will add |S| to x then iterate from y to x and calculate
the number of flip bits.
Now, if x > y, we will swap x and y and calculate the answer using above approach. Then
output the opposite of the result .
To calculate the number of flip bits, just store the current bit of index and check if next
index have the same bit as current. If yes then do nothing else change the current bit to
the bit of the next index and increment minimum bit by 1.
Below is the C++ implementation of this approach:
1372
Chapter 217. Minimum bit changes in Binary Circular array to reach a index
int valAnticlockwise = 0;
cur = s[y];
x += s.length();
for (int i = y; i <= x; i++) {
// if current bit is not equal
// to next index bit.
if (s[i] != cur) {
cur = s[i];
valAnticlockwise++;
}
}
// Finding whether Clockwise or Anti-clockwise
// path take minimum flip.
if (valClockwise <= valAnticlockwise) {
if (!isOpposite)
cout << "Clockwise "
<< valClockwise << endl;
else
cout << "Anti-clockwise "
<< valAnticlockwise << endl;
}
else {
if (!isOpposite)
cout << "Anti-clockwise "
<< valAnticlockwise << endl;
else
cout << "Clockwise "
<< valClockwise << endl;
}
}
// Driven Program
int main()
{
int x = 0, y = 8;
string s = "000110";
minimumFlip(s, x, y);
return 0;
}
Output
Anti-clockwise 0
1373
Chapter 217. Minimum bit changes in Binary Circular array to reach a index
Source
https://www.geeksforgeeks.org/minimum-bit-changes-binary-circular-array-reach-index/
1374
Chapter 218
• AND operation as : temp = ai & aj, ai = temp & ai, aj = temp & aj
• OR operation as : temp = ai | aj, ai = temp | ai, aj = temp | aj
• XOR operation as : temp = ai ^ aj, ai = temp ^ ai, aj = temp ^ aj
Explanation : First of all let’s understand the working of all three operation.
1. AND operation as : temp = ai & aj, ai = temp & ai, aj = temp & aj
2. OR operation as : temp = ai | aj, ai = temp | ai, aj = temp | aj
1375
Chapter 218. Minimum bitwise operations to convert given a into b.
1376
Chapter 218. Minimum bitwise operations to convert given a into b.
string b = b1.to_string();
// check where ai and bi are different
// and count n where ai = 1 and m where ai = 0
int n = 0, m = 0;
for (int i = 0; i < b.size(); i++) {
if (b[i] != a[i]) {
if (a[i] == '1')
n++;
else
m++;
}
}
// return result
return max(n, m);
}
// driver program
int main()
{
bitset<32> a = 14, b = 1;
cout << minOp(a, b);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/minimum-bitwise-operations-to-convert-given-a-into-b/
1377
Chapter 219
Input : 8314
Output: 81 2
Explanation: If we remove 3 and 4 number becomes 81 which is a perfect square.
Input : 57
Output : -1
The idea is to generate all possible subsequences and return optimal string using set bits.
Let’s suppose we have a string 8314. And using set bits we form all possible subsequences
i.e.,
8, 3, 83, 1, 81, 31, 831, 4, 84, 34, 834, 14, 814, 314, 8314.
After forming all possible subsequences, we check which one is the perfect square. And we
return a perfect square number which has the minimum length.
In above example, three perfect squares are 1 4 and 81, so answer would be 81 because 81
has the max length 2.
C++
1378
Chapter 219. Minimum digits to remove to make a number Perfect Square
1379
Chapter 219. Minimum digits to remove to make a number Perfect Square
}
if (ans == -1)
return ans;
else {
// print PerfectSquare
cout << num << " ";
return n - ans;
}
}
// Driver code
int main()
{
cout << perfectSquare("8314") << endl;
cout << perfectSquare("753") << endl;
return 0;
}
Java
1380
Chapter 219. Minimum digits to remove to make a number Perfect Square
for (int j = 0; j < n; j++) {
// to check jth bit is set or not.
if (((i >> j) & 1) == 1) {
str += s.charAt(j);
}
}
// we do not consider a number
// with leading zeros
if (str.charAt(0) != '0') {
// convert our temporary
// string into integer
int temp = 0;
for (int j = 0; j <
str.length(); j++)
temp = temp * 10 +
(int)(str.charAt(j) - '0');
int k = (int)Math.sqrt(temp);
// checking temp is perfect
// square or not.
if (k * k == temp) {
// taking maximum sized string
if (ans < (int)str.length()) {
ans = (int)str.length();
num = str;
}
}
}
}
if (ans == -1)
return ans;
else {
// print PerfectSquare
System.out.print(num + " ");
return n - ans;
}
}
// Driver code
public static void main(String args[])
1381
Chapter 219. Minimum digits to remove to make a number Perfect Square
{
System.out.println(perfectSquare("8314"));
System.out.println(perfectSquare("753"));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
1382
Chapter 219. Minimum digits to remove to make a number Perfect Square
temp = 0;
for j in range(0, len(str)) :
temp = (temp * 10 +
(ord(str[j]) - ord('0')))
k = int(math.sqrt(temp))
# checking temp is perfect
# square or not.
if (k * k == temp) :
# taking maximum sized
# string
if (ans < len(str)) :
ans = len(str)
num = str
if (ans == -1) :
return ans
else :
# print PerfectSquare
print ("{} ".format(num), end="")
return n - ans
# Driver code
print (perfectSquare("8314"))
print (perfectSquare("753"));
# This code is contributed by
# manishshaw1.
C#
1383
Chapter 219. Minimum digits to remove to make a number Perfect Square
1384
Chapter 219. Minimum digits to remove to make a number Perfect Square
PHP
<?php
// PHP program to find required
// minimum digits need to remove
// to make a number perfect squre
// function to check minimum
// number of digits should be
// removed to make this number
// a perfect square
function perfectSquare($s)
{
// size of the string
$n = strlen($s);
// our final answer
$ans = -1;
// to store string which
// is perfect square.
$num = "";
// We make all possible
// subsequences
for ($i = 1; $i < (1 << $n); $i++)
{
$str = "";
for ($j = 0; $j < $n; $j++)
{
1385
Chapter 219. Minimum digits to remove to make a number Perfect Square
1386
Chapter 219. Minimum digits to remove to make a number Perfect Square
Output :
81 2
-1
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/required-minimum-digits-remove-number-make-perfect-square/
1387
Chapter 220
Input : n = 14, k = 2
Output : Min Flips = 1
Explanation :
Binary representation of 14 = 1110
Largest 4-digit Binary number with
2 set bit = 1100
Conversion from 1110 to 1100
requires 1 flipping
Input : n = 145, k = 4
Output : Min Flips = 3
Explanation :
Binary representation of 145 = 10010001
Largest 8-digit Binary number with
4 set bit = 11110000
Conversion from 10010001 to 11110000
requires 3 flipping
1388
Chapter 220. Minimum flips required to maximize a number with k set bits
For the given number n and k find the largest number possible with k-set bits and having
exactly same number of bits as n has as :
C++
1389
Chapter 220. Minimum flips required to maximize a number with k set bits
// function for finding min flip
int minFlip(int n, int k)
{
// number of bits in n
int size = log2(n) + 1;
// Find the largest number of
// same size with k set bits
int max = pow(2, k) - 1;
max = max << (size - k);
// Count bit differences to find
// required flipping.
int xorValue = (n ^ max);
return (setBit(xorValue));
}
// driver program
int main()
{
int n = 27, k = 3;
cout << "Min Flips = " << minFlip(n, k);
return 0;
}
Java
1390
Chapter 220. Minimum flips required to maximize a number with k set bits
// function for finding min flip
static int minFlip(int n, int k)
{
// number of bits in n
int size = (int)(Math.log(n) /
Math.log(2)) + 1;
// Find the largest number of
// same size with k set bits
int max = (int)Math.pow(2, k) - 1;
max = max << (size - k);
// Count bit differences to find
// required flipping.
int xorValue = (n ^ max);
return (setBit(xorValue));
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 27, k = 3;
System.out.println("Min Flips = "+
minFlip(n, k));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python 3
1391
Chapter 220. Minimum flips required to maximize a number with k set bits
return count
# function for
# finding min flip
def minFlip(n, k):
# number of bits in n
size = int(math.log(n) /
math.log(2) + 1)
# Find the largest number of
# same size with k set bits
max = pow(2, k) - 1
max = max << (size - k)
# Count bit differences to
# find required flipping.
xorValue = (n ^ max)
return (setBit(xorValue))
# Driver Code
n = 27
k = 3
print("Min Flips = " ,
minFlip(n, k))
# This code is contributed
# by Smitha
C#
1392
Chapter 220. Minimum flips required to maximize a number with k set bits
PHP
<?php
// PHP for finding min flip
// for maximizing given n
// function for finding set bit
function setBit($xorValue)
{
$count = 0;
while ($xorValue)
{
if ($xorValue % 2)
$count++;
$xorValue /= 2;
1393
Chapter 220. Minimum flips required to maximize a number with k set bits
}
// return count of set bit
return $count;
}
// function for finding min flip
function minFlip($n, $k)
{
// number of bits in n
$size = log($n) + 1;
// Find the largest number of
// same size with k set bits
$max = pow(2, $k) - 1;
$max = $max << ($size - $k);
// Count bit differences to find
// required flipping.
$xorValue = ($n ^ $max);
return (setBit($xorValue));
}
// Driver Code
$n = 27; $k = 3;
echo "Min Flips = " , minFlip($n, $k);
// This code is contributed by vt_m.
?>
Output :
Min Flips = 3
Source
https://www.geeksforgeeks.org/minimum-flips-required-to-maximize-a-number-with-k-set-bits/
1394
Chapter 221
Minimum flips to make all 1s in left and 0s in right | Set 1 (Using Bitmask) - GeeksforGeeks
Given a binary array, we can flip all the 1 are in the left part and all the 0 to the right
part.Calculate the minimum flips required to make all 1s in left and all 0s in right.
Examples:
Input: 1011000
Output: 1
1 flip is required to make it 1111000.
Input : 00001
Output : 2
2 flips required to make it 10000.
For solving this problem we use bitmasking. First, we convert this array to string, then
we find the equivalent decimal number of that binary string. We try all masks with all
possibilities of 1s in left and 0s in right. We iterate a loop till decimal number becomes zero.
Each time we will do bitwise XOR of the number with mask and number of ones in XOR
value will be the number of flips required. We decrease n by 1 and update the mask.
1-Take binary array as input
2-Convert array to string and then equivalent decimal number(num)
3-Take initial mask value and iterate till num <= 0
4-Find required flips using (num XOR mask)
5-Find minimum flips and decrease num and update mask
6-Return the minimum count
1395
Chapter 221. Minimum flips to make all 1s in left and 0s in right | Set 1 (Using Bitmask)
1396
Chapter 221. Minimum flips to make all 1s in left and 0s in right | Set 1 (Using Bitmask)
return c;
}
public static void main(String[] args)
{
int[] nums = { 1, 0, 1, 1, 0, 0, 0 };
int n = findMiniFlip(nums);
System.out.println(n);
}
}
Output:
Source
https://www.geeksforgeeks.org/minimum-flips-make-1s-left-0s-right-set-1-using-bitmask/
1397
Chapter 222
Input : 6
Output : 3
Binary representation of 6 is 0000….0110. Smallest number with same number
of set bits 0000….0011.
Input : 11
Output : 7
Simple Approach:
1. Find binary representation of the number using simple decimal to binary representation
technique.
2. Count number of set bits in the binary representation equal to ‘n’.
3. Create a binary representation with it’s ‘n’ least significant bits set to 1.
4. Convert the binary representation back to the number.
Efficient Approach:
1. Just measure the number of 1’s present in the bit representation of the number.
2. (Number of set bits raised to the power of 2) – 1 represents the minimized number.
C++
1398
Chapter 222. Minimum number using set bits of a given number
Java
1399
Chapter 222. Minimum number using set bits of a given number
C#
1400
Chapter 222. Minimum number using set bits of a given number
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output :
Note : The above code uses GCC specific functions. If we wish to write code for other
compilers, we may use Count set bits in an integer.
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/minimum-number-using-set-bits-given-number/
1401
Chapter 223
Input: K = 7
Output: 6
1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 = 7
Input: K = 10
Output: Not Possible
Approach: This problem is similar to the Calculate XOR from 1 to n. Below are the
conditions to be checked:
1. If k = 0, then N = 3.
2. If k = 1, then N = 1.
3. If k % 4 = 0, then N = k.
4. If k % 4 = 3, then N = k-1.
C++
1402
Chapter 223. Minimum value of N such that xor from 1 to N is equal to K
#include <bits/stdc++.h>
using namespace std;
// Function to find the value of N
int findN(int k)
{
// variable to store the result
int ans;
// handling case for '0'
if (k == 0)
ans = 3;
// handling case for '1'
if (k == 1)
ans = 1;
// when number is completely divided by
// 4 then minimum 'x' will be 'k'
else if (k % 4 == 0)
ans = k;
// when number divided by 4 gives 3 as
// remainder then minimum 'x' will be 'k-1'
else if (k % 4 == 3)
ans = k - 1;
// else it is not possible to get
// k for any value of x
else
ans = -1;
return ans;
}
// Driver code
int main()
{
// let the given number be 7
int k = 7;
int res = findN(k);
if (res == -1)
cout << "Not possible";
else
cout << res;
1403
Chapter 223. Minimum value of N such that xor from 1 to N is equal to K
return 0;
}
Java
// Java implementation of
// above approach
import java.io.*;
class GFG
{
// Function to find the
// value of N
static int findN(int k)
{
// variable to store
// the result
int ans;
// handling case for '0'
if (k == 0)
ans = 3;
// handling case for '1'
if (k == 1)
ans = 1;
// when number is completely
// divided by 4 then minimum
// 'x' will be 'k'
else if (k % 4 == 0)
ans = k;
// when number divided by 4
// gives 3 as remainder then
// minimum 'x' will be 'k-1'
else if (k % 4 == 3)
ans = k - 1;
// else it is not possible to
// get k for any value of x
else
ans = -1;
return ans;
}
1404
Chapter 223. Minimum value of N such that xor from 1 to N is equal to K
// Driver code
public static void main (String[] args)
{
// let the given number be 7
int k = 7;
int res = findN(k);
if (res == -1)
System.out.println("Not possible");
else
System.out.println(res);
}
}
// This code is contributed
// by inder_verma
C#
// C# implementation of
// above approach
using System;
class GFG
{
// Function to find the
// value of N
static int findN(int k)
{
// variable to store
// the result
int ans;
// handling case for ‘0’
if (k == 0)
ans = 3;
// handling case for ‘1’
if (k == 1)
ans = 1;
// when number is completely
// divided by 4 then minimum
// ‘x’ will be ‘k’
else if (k % 4 == 0)
ans = k;
// when number divided by 4
// gives 3 as remainder then
1405
Chapter 223. Minimum value of N such that xor from 1 to N is equal to K
1406
Chapter 223. Minimum value of N such that xor from 1 to N is equal to K
Improved By : inderDuMCA
Source
https://www.geeksforgeeks.org/minimum-value-of-n-such-that-xor-from-1-to-n-is-equal-to-k/
1407
Chapter 224
Input : n = 7, p = 2, b = 0
Output : 3
7 is 00000111 after clearing bit at
2rd position, it becomes 0000011.
Input : n = 7, p = 3, b = 1
Output : 15
7 is 00000111 after setting bit at
3rd position it becomes 00001111.
1408
Chapter 224. Modify a bit at a given position
C++
Java
1409
Chapter 224. Modify a bit at a given position
}
}
// This code is contributed by m_kit
C#
PHP
<?php
// PHP program to modify a bit
// at position p in n to b.
// Returns modified n.
function modifyBit($n, $p, $b)
{
$mask = 1 << $p;
return ($n & ~$mask) |
(($b << $p) & $mask);
}
1410
Chapter 224. Modify a bit at a given position
// Driver code
echo modifyBit(6, 2, 0),"\n";
echo modifyBit(6, 5, 1) ,"\n";
// This code is contributed by ajit
?>
Output :
2
38
Improved By : jit_t
Source
https://www.geeksforgeeks.org/modify-bit-given-position/
1411
Chapter 225
C++
1412
Chapter 225. Multiples of 4 (An Interesting Method)
int XOR = 0;
for (int i = 1; i <= n; i++)
XOR = XOR ^ i;
// If XOR is equal n, then return true
return (XOR == n);
}
// Driver code to print multiples of 4
int main()
{
// Printing multiples of 4 using above method
for (int n=0; n<=42; n++)
if (isMultipleOf4(n))
cout << n << " ";
return 0;
}
Java
1413
Chapter 225. Multiples of 4 (An Interesting Method)
Python 3
C#
1414
Chapter 225. Multiples of 4 (An Interesting Method)
return false;
// Find XOR of all numbers
// from 1 to n
int XOR = 0;
for (int i = 1; i <= n; i++)
XOR = XOR ^ i;
// If XOR is equal n, then
// return true
return (XOR == n);
}
// Driver method
public static void Main()
{
// Printing multiples of 4
// using above method
for (int n = 0; n <= 42; n++)
{
if (isMultipleOf4(n))
Console.Write(n+" ");
}
}
}
// This code is contributed by Smitha.
PHP
<?php
// PHP program to check if
// a number is multiple of 4.
// Returns true if n is
// a multiple of 4.
function isMultipleOf4($n)
{
if ($n == 1)
return false;
// Find XOR of all
// numbers from 1 to n
$XOR = 0;
for ($i = 1; $i <= $n; $i++)
$XOR = $XOR ^ $i;
1415
Chapter 225. Multiples of 4 (An Interesting Method)
Output :
0 4 8 12 16 20 24 28 32 36 40
C++
1416
Chapter 225. Multiples of 4 (An Interesting Method)
return true;
return (((n>>2)<<2) == n);
}
// Driver code to print multiples of 4
int main()
{
// Printing multiples of 4 using above method
for (int n=0; n<=42; n++)
if (isMultipleOf4(n))
cout << n << " ";
return 0;
}
Java
C#
1417
Chapter 225. Multiples of 4 (An Interesting Method)
// Returns true if n is a multiple
// of 4.
static bool isMultipleOf4(int n)
{
if (n == 0)
return true;
return (((n >> 2) << 2) == n);
}
// Driver code to print multiples
// of 4
static void Main()
{
// Printing multiples of 4 using
// above method
for (int n = 0; n <= 42; n++)
if (isMultipleOf4(n))
Console.Write(n + " ");
}
}
// This code is contributed by Anuj_67
PHP
<?php
// PHP program to check if
// a number is multiple of 4.
// Returns true if n is
// a multiple of 4.
function isMultipleOf4($n)
{
if ($n == 0)
return true;
return ((($n >> 2) << 2) == $n);
}
// Driver Code
// Printing multiples of 4
// using above method
for ($n = 0; $n <= 42; $n++)
if (isMultipleOf4($n))
1418
Chapter 225. Multiples of 4 (An Interesting Method)
Output :
0 4 8 12 16 20 24 28 32 36 40
As we can see that the main idea to find multiplicity of 4 is to check the least two significant
bits of the given number. We know that for any even number, the least significant bit is
always ZERO (i.e. 0). Similarly, for any number which is multiple of 4 will have least two
significant bits as ZERO. And with the same logic, for any number to be multiple of 8, least
three significant bits will be ZERO. That’s why we can use AND operator (&) as well with
other operand as 0x3 to find multiplicity of 4.
Improved By : vt_m, jit_t, Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/multiples-4-interesting-method/
1419
Chapter 226
Input: n = 25 , m = 13
Output: 325
Input: n = 50 , m = 16
Output: 800
We can solve this problem with the shift operator. The idea is based on the fact that every
number can be represented in binary form. And multiplication with a number is equivalent
to multiplication with powers of 2. Powers of 2 can be obtained using left shift operator.
Check for every set bit in the binary representation of m and for every set bit left shift n,
count times where count if place value of the set bit of m and add that value to answer.
C++
1420
Chapter 226. Multiplication of two numbers with shift operator
{
int ans = 0, count = 0;
while (m)
{
// check for set bit and left
// shift n, count times
if (m % 2 == 1)
ans += n << count;
// increment of place value (count)
count++;
m /= 2;
}
return ans;
}
// Driver code
int main()
{
int n = 20 , m = 13;
cout << multiply(n, m);
return 0;
}
Java
1421
Chapter 226. Multiplication of two numbers with shift operator
return ans;
}
// Driver code
public static void main (String[] args)
{
int n = 20, m = 13;
System.out.print( multiply(n, m) );
}
}
// This code is contributed by Anant Agarwal.
C#
1422
Chapter 226. Multiplication of two numbers with shift operator
PHP
<?php
// PHP program to find multiplication
// of two number without use of
// multiplication operator
// Function for multiplication
function multiply( $n, $m)
{
$ans = 0; $count = 0;
while ($m)
{
// check for set bit and left
// shift n, count times
if ($m % 2 == 1)
$ans += $n << $count;
// increment of place value (count)
$count++;
$m /= 2;
}
return $ans;
}
// Driver code
$n = 20 ; $m = 13;
echo multiply($n, $m);
// This code is contributed by anuj_67.
?>
Output :
260
1423
Chapter 226. Multiplication of two numbers with shift operator
Related Article:
Russian Peasant (Multiply two numbers using bitwise operators)
Improved By : vt_m
Source
https://www.geeksforgeeks.org/multiplication-two-numbers-shift-operator/
1424
Chapter 227
Input : x = 25, n = 3
Output : 200
25 multiplied by 2 raised to power 3
is 200.
Input : x = 70, n = 2
Output : 280
C++
1425
Chapter 227. Multiplication with a power of 2
if (n == 1)
return 2;
return power2(n / 2) *
power2(n / 2);
}
ll multiply(ll x, ll n)
{
return x * power2(n);
}
// Driven program
int main()
{
ll x = 70, n = 2;
cout<<multiply(x, n);
return 0;
}
Java
1426
Chapter 227. Multiplication with a power of 2
{
long x = 70, n = 2;
System.out.println(multiply(x, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
// Simple C# program
// to compute x * (2^n)
using System;
class GFG {
// Returns 2 raised to power n
static long power2(long n)
{
1427
Chapter 227. Multiplication with a power of 2
if (n == 0)
return 1;
if (n == 1)
return 2;
return power2(n / 2)
* power2(n / 2);
}
static long multiply(long x, long n)
{
return x * power2(n);
}
/* Driver program */
public static void Main()
{
long x = 70, n = 2;
Console.WriteLine(multiply(x, n));
}
}
// This code is contributed by Vt_m.
PHP
<?php
// Simple PHP program
// to compute x * (2^n)
// Returns 2 raised to power n
function power2($n)
{
if ($n == 0)
return 1;
if ($n == 1)
return 2;
return power2($n / 2) *
power2($n / 2);
}
function multiply( $x, $n)
{
return $x * power2($n);
1428
Chapter 227. Multiplication with a power of 2
}
// Driver Code
$x = 70; $n = 2;
echo multiply($x, $n);
// This code is contributed by ajit
?>
Output :
280
Java
1429
Chapter 227. Multiplication with a power of 2
return x << n;
}
/* Driver program to test above function */
public static void main(String[] args)
{
long x = 70, n = 2;
System.out.println(multiply(x, n));
}
}
//This code is contributed by Arnav Kr. Mandal.
Python3
C#
1430
Chapter 227. Multiplication with a power of 2
}
//This code is contributed by vt_m.
PHP
<?php
// Efficient PHP program to compute x * (2^n)
function multiply($x, $n)
{
return $x << $n;
}
// Driver Code
$x = 70;
$n = 2;
echo multiply($x, $n);
// This code is contributed by ajit
?>
Output :
280
Source
https://www.geeksforgeeks.org/multiplication-power-2/
1431
Chapter 228
Examples :
Input: 2
Output: 7
Input: 5
Output: 17 (Ignore the digits after decimal point)
Solution:
1. We can get x*3.5 by adding 2*x, x and x/2. To calculate 2*x, left shift x by 1 and to
calculate x/2, right shift x by 2.
C++
1432
Chapter 228. Multiply a given Integer with 3.5
int main()
{
int x = 4;
printf("%d", multiplyWith3Point5(x));
getchar();
return 0;
}
Java
Python3
1433
Chapter 228. Multiply a given Integer with 3.5
C#
// C# Program to multiply
// a number with 3.5
using System;
class GFG
{
static int multiplyWith3Point5(int x)
{
return (x<<1) + x + (x>>1);
}
/* Driver program to test above functions*/
public static void Main()
{
int x = 2;
Console.Write(multiplyWith3Point5(x));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to multiply
// a number with 3.5
function multiplyWith3Point5( $x)
{
return ($x << 1) + $x + ($x >> 1);
}
// Driver Code
$x = 4;
echo multiplyWith3Point5($x);
// This code is contributed by vt_m.
?>
2. Another way of doing this could be (8*x – x)/2 (See below code). Thanks to Ajaym for
suggesting this.
1434
Chapter 228. Multiply a given Integer with 3.5
#include <stdio.h>
int multiplyWith3Point5(int x)
{
return ((x<<3) - x)>>1;
}
Improved By : vt_m
Source
https://www.geeksforgeeks.org/multiply-an-integer-with-3-5/
1435
Chapter 229
Input : n = 50
Output: 500
// multiplication of 50 with 10 is = 500
Input : n = 16
Output: 160
// multiplication of 16 with 10 is = 160
A simple solution for this problem is to run a loop and add n with itself 10 times. Here
we need to perform 10 operations.
A better solution is to use bit manipulation. We have to multiply n with 10 i.e; n*10, we
can write this as n*(2+8) = n*2 + n*8 and since we are not allowed to use multiplication
operator we can do this using left shift bitwise operator. So n*10 = n<<1 + n<<3.
C++
1436
Chapter 229. Multiply a number with 10 without using multiplication operator
Java
Python 3
1437
Chapter 229. Multiply a number with 10 without using multiplication operator
# Function to find multiplication
# of n with 10 without usng
# multiplication operator
def multiplyTen(n):
return (n << 1) + (n << 3)
# Driver program to run the case
n = 50
print (multiplyTen(n))
# This code is contributed by
# Smitha
C#
PHP
<?php
// PHP program to multiply a
// number with 10 using
1438
Chapter 229. Multiply a number with 10 without using multiplication operator
// bitwise operators
// Function to find multiplication
// of n with 10 without using
// multiplication operator
function multiplyTen($n)
{
return ($n << 1) + ($n << 3);
}
// Driver Code
$n = 50;
echo multiplyTen($n);
// This code is contributed by nitin mittal.
?>
Output:
500
Source
https://www.geeksforgeeks.org/multiply-number-10-without-using-multiplication-operator/
1439
Chapter 230
Input : 4
Output :16
Input :5
Output :20
Explanation Case 1:- n=4 the binary of 4 is 100 and now shift two bit right then 10000
now the number is 16 that is multiply 4*4=16 ans.
Approach :- (n<<2) shift two bit right
C++
1440
Chapter 230. Multiply any Number with 4 using Bitwise Operator
Java
Python 3
1441
Chapter 230. Multiply any Number with 4 using Bitwise Operator
# function the return multiply
# a number with 4 using bitwise
# operator
def multiplyWith4(n):
# returning a number with
# multipy with 4 using2
# bit shifring right
return (n << 2)
# derive function
n = 4
print(multiplyWith4(n))
# This code is contributed
# by Smitha
C#
1442
Chapter 230. Multiply any Number with 4 using Bitwise Operator
PHP
<?php
// PHP program to multiply
// a number with 4 using
// Bitwise Operator
// function the return
// multiply a number
// with 4 using bitwise
// operator
function multiplyWith4($n)
{
// returning a number
// with multipy with
// 4 using2 bit
// shifting right
return ($n << 2);
}
// Driver Code
$n = 4;
echo multiplyWith4($n),"\n";
// This code is contributed by Ajit.
?>
Output :-
16
Source
https://www.geeksforgeeks.org/multiply-number-4-using-bitwise-operator/
1443
Chapter 231
a = a << 3 + a << 1;
a = a<<3 - a;
or
a = a<<2 + a<<1 + a;
1444
Chapter 231. Multiplying a variable with a constant without using multiplication operator
#include<iostream>
using namespace std;
// Returns n * 7
int multiplyBySeven(int n)
{
// OR (n << 2) + (n << 1) + n
return (n << 3) - n;
}
// Returns n * 12
int multiplyByTwelve(int n)
{
return (n << 3) + (n << 2);
}
int main()
{
cout << multiplyBySeven(5) << endl;
cout << multiplyByTwelve(5) << endl;
return 0;
}
Java
class GFG {
// Returns n * 7
static int multiplyBySeven(int n)
{
// OR (n << 2) + (n << 1) + n
return (n << 3) - n;
}
// Returns n * 12
static int multiplyByTwelve(int n)
{
return (n << 3) + (n << 2);
}
// Driver code
public static void main(String[] args)
{
System.out.println(multiplyBySeven(5));
System.out.println(multiplyByTwelve(5));
}
}
1445
Chapter 231. Multiplying a variable with a constant without using multiplication operator
// This code is contributed by Anant Agarwal.
Python3
C#
// C# program to Multiplying a
// variable with a constant
using System;
class GFG
{
// Returns n * 7
static int multiplyBySeven(int n)
{
// OR (n << 2) + (n << 1) + n
return (n << 3) - n;
}
// Returns n * 12
static int multiplyByTwelve(int n)
{
return (n << 3) + (n << 2);
}
// Driver code
public static void Main()
1446
Chapter 231. Multiplying a variable with a constant without using multiplication operator
{
Console.WriteLine(multiplyBySeven(5));
Console.WriteLine(multiplyByTwelve(5));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program of multiply operator
// Returns n * 7
function multiplyBySeven($n)
{
return ($n << 3) - $n;
}
// Returns n * 12
function multiplyByTwelve($n)
{
return ($n << 3) + ($n << 2);
}
// Driver Code
echo multiplyBySeven(5), "\n";
echo multiplyByTwelve(5), "\n";
// This code is contributed by Ajit
?>
Output :
35
60
We just need to find the combination of powers of 2. Also, this comes really handy when
we have a very large dataset and each one of them requires multiplication with the same
constant as bitwise operators are faster as compared to mathematical operators.
Improved By : jit_t
Source
https://www.geeksforgeeks.org/multiplying-variable-constant-without-using-multiplication-operator/
1447
Chapter 232
Next greater integer having one more number of set bits - GeeksforGeeks
Given a positive integer ‘n’ having ‘x’ number of set bits in its binary representation. The
problem is to find the next greater integer(smallest integer greater than n), having (x+1)
number of set bits in its binary representation.
Examples :
Input : 10
Output : 11
(10)10 = (1010)2
is having 2 set bits.
(11)10 = (1011)2
is having 3 set bits and is the next greater.
Input : 39
Output : 47
1. Find the position of the rightmost unset bit(considering last bit at position 0, second
last bit at position 1 and so on) in the binary representation of n.
2. Let the position be represented by pos.
3. Set the bit at position pos. Refer this post.
4. If there are no unset bits in the binary representation, then perform bitwise left shift
by 1 on the given number and then add 1 to it.
1448
Chapter 232. Next greater integer having one more number of set bits
C++
Java
1449
Chapter 232. Next greater integer having one more number of set bits
Python3
1450
Chapter 232. Next greater integer having one more number of set bits
C#
1451
Chapter 232. Next greater integer having one more number of set bits
PHP
<?php
// PHP implementation to find the
// next greater integer with
// one more number of set bits
// function to find the position
// of rightmost set bit. Returns
// -1 if there are no set bits
function getFirstSetBitPos($n)
{
return (log($n & -$n + 1)) - 1;
}
// function to find the
// next greater integer
function nextGreaterWithOneMoreSetBit($n)
{
// position of rightmost unset bit of n
// by passing ~n as argument
1452
Chapter 232. Next greater integer having one more number of set bits
$pos = getFirstSetBitPos(~$n);
// if n consists of unset bits, then
// set the rightmost unset bit
if ($pos > -1)
return (1 << $pos) | $n;
//n does not consists of unset bits
return (($n << 1) + 1);
}
// Driver Code
$n = 10;
echo "Next greater integer = ",
nextGreaterWithOneMoreSetBit($n);
// This code is contributed by Ajit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/next-greater-integer-one-number-set-bits/
1453
Chapter 233
x = 156
10
x = 10011100
(2)
10011100
00011100 - right most string of 1's in x
00000011 - right shifted pattern except left most bit ------> [A]
00010000 - isolated left most bit of right most 1's pattern
00100000 - shiftleft-ed the isolated bit by one position ------> [B]
10000000 - left part of x, excluding right most 1's pattern ------> [C]
10100000 - add B and C (OR operation) ------> [D]
10100011 - add A and D which is required number 163
1454
Chapter 233. Next higher number with same number of set bits
(10)
After practicing with few examples, it easy to understand. Use the below given program for
generating more sets.
Program Design:
We need to note few facts of binary numbers. The expression x & -x will isolate right most
set bit in x (ensuring x will use 2’s complement form for negative numbers). If we add the
result to x, right most string of 1’s in x will be reset, and the immediate ‘0’ left to this
pattern of 1’s will be set, which is part [B] of above explanation. For example if x = 156, x
& -x will result in 00000100, adding this result to x yields 10100000 (see part D). We left
with the right shifting part of pattern of 1’s (part A of above explanation).
There are different ways to achieve part A. Right shifting is essentially a division operation.
What should be our divisor? Clearly, it should be multiple of 2 (avoids 0.5 error in right
shifting), and it should shift the right most 1’s pattern to right extreme. The expression (x
& -x) will serve the purpose of divisor. An EX-OR operation between the number X and
expression which is used to reset right most bits, will isolate the rightmost 1’s pattern.
A Correction Factor:
Note that we are adding right most set bit to the bit pattern. The addition operation causes
a shift in the bit positions. The weight of binary system is 2, one shift causes an increase by
a factor of 2. Since the increased number (rightOnesPattern in the code) being used twice,
the error propagates twice. The error needs to be corrected. A right shift by 2 positions
will correct the result.
The popular name for this program is same number of one bits.
C++
#include<iostream>
using namespace std;
typedef unsigned int uint_t;
// this function returns next higher number with same number of set bits as x.
uint_t snoob(uint_t x)
{
uint_t rightOne;
uint_t nextHigherOneBit;
uint_t rightOnesPattern;
uint_t next = 0;
if(x)
{
1455
Chapter 233. Next higher number with same number of set bits
Python 3
1456
Chapter 233. Next higher number with same number of set bits
# reset the pattern and
# set next higher bit
# left part of x will
# be here
nextHigherOneBit = x + int(rightOne)
# nextHigherOneBit is
# now part [D] of the
# above explanation.
# isolate the pattern
rightOnesPattern = x ^ int(nextHigherOneBit)
# right adjust pattern
rightOnesPattern = (int(rightOnesPattern) /
int(rightOne))
# correction factor
rightOnesPattern = int(rightOnesPattern) >> 2
# rightOnesPattern is now part
# [A] of the above explanation.
# integrate new pattern
# (Add [D] and [A])
next = nextHigherOneBit | rightOnesPattern
return next
# Driver Code
x = 156
print("Next higher number with " +
"same number of set bits is",
snoob(x))
# This code is contributed by Smita
1. Write a program to find a number immediately smaller than given, with same number
of logic 1 bits? (Pretty simple)
2. How to count or generate the subsets available in the given set?
References:
1457
Chapter 233. Next higher number with same number of set bits
2. Hackers Delight by Warren (An excellent and short book on various bit magic algo-
rithms, a must for enthusiasts)
3. C A Reference Manual by Harbison and Steele (A good book on standard C, you can
access code part of this post here).
– Venki. Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Improved By : Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/
1458
Chapter 234
Input : n = 2
Output : 4
The given set A = {1, 2}. The following
are reflexive relations on A * A :
{{1, 1), (2, 2)}
{(1, 1), (2, 2), (1, 2)}
{(1, 1), (2, 2), (1, 2), (2, 1)}
{(1, 1), (2, 2), (2, 1)}
Input : n = 3
Output : 64
The given set is {1, 2, 3}. There are
64 reflexive relations on A * A :
Explanation :
Reflexive Relation : A Relation R on A a set A is said to be Reflexive if xRx for every
element of x ? A.
2
The number of reflexive relations on an n-element set is 2n – n
1459
Chapter 234. Number of Reflexive Relations on a Set
If we take a closer look the matrix, we can notice that the size of matrix is n2 .
The n diagonal entries are fixed. For remaining n2 – n entries, we have choice
2
to either fill 0 or 1. So there are total 2n – n ways of filling the matrix.
CPP
Java
1460
Chapter 234. Number of Reflexive Relations on a Set
static int countReflexive(int n)
{
// Return 2^(n*n - n)
return (1 << (n*n - n));
}
// Driver function
public static void main (String[] args) {
int n = 3;
System.out.println(countReflexive(n));
}
}
// This code is contributed by Gitanjali.
Python3
C#
1461
Chapter 234. Number of Reflexive Relations on a Set
static int countReflexive(int n)
{
// Return 2^(n*n - n)
return (1 << (n*n - n));
}
// Driver function
public static void Main () {
int n = 3;
Console.WriteLine(countReflexive(n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to count
// reflexive relations on a
// set of first n natural numbers.
function countReflexive($n)
{
// Return 2^(n * n - n)
return (1 << ($n * $n - $n));
}
//Driver code
$n = 3;
echo countReflexive($n);
// This code is contributed by mits
?>
Output :
64
Source
https://www.geeksforgeeks.org/number-reflexive-relations-set/
1462
Chapter 235
Input : 5
Output : 3
Explanation :
Integers with odd number of
set bits in range 1 to 5 :
0 contains 0 set bits
1 contains 1 set bits
2 contains 1 set bits
3 contains 2 set bits
4 contains 1 set bits
5 contains 2 set bits
Input : 10
Output : 5
Explanation :
Integers with odd set bits are 1, 2,
4, 7 and 8.
1463
Chapter 235. Number of integers with odd number of set bits
If n is odd then there are total n+1 integers smaller than or equal to n (0, 1, 2
… n) and half of these integers contain odd number of set bits.
How to handle case when n is even? We know result for n-1. We count set bits in n and
add 1 to n/2 if the count is odd. Else we return n/2.
C++
Java
1464
Chapter 235. Number of integers with odd number of set bits
class GFG
{
// function that returns the
// number of integers with
// odd number of set bits
static int countWithOddSetBits(int n)
{
// If n is odd, then half
// of the integers in
// (0, 1, .. n) contain
// odd number of set bits.
if (n % 2 != 0)
return (n + 1) / 2;
// If n is even, we know
// result for n-1. We
// explicitly compute set
// bit count in n.
int count = (n);
int ans = n / 2;
if (count % 2 != 0)
ans++;
return ans;
}
// Driver Code
public static void main (String[] args)
{
int n = 10;
System.out.println( countWithOddSetBits(n));
}
}
// This code is contributed by aj_36
C#
1465
Chapter 235. Number of integers with odd number of set bits
PHP
<?php
// PHP code to find numbers with
// odd number of set bits
// function that returns the number
// of integers with odd number of
// set bits
function countWithOddSetBits($n)
{
// If n is odd, then half of
// the integers in (0, 1, .. n)
// contain odd number of set bits.
if ($n % 2 != 0)
1466
Chapter 235. Number of integers with odd number of set bits
return ($n + 1) / 2;
// If n is even, we know result
// for n-1. We explicitly compute
// set bit count in n.
$count = ($n);
$ans = $n / 2;
if ($count % 2 != 0)
$ans++;
return $ans;
}
// Driver code
$n = 10;
echo countWithOddSetBits($n);
// This code is contributed by aj_36
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/number-integers-odd-number-set-bits/
1467
Chapter 236
Examples:
Method 1 (Brute Force): A possible brute-force solution is to form all possible concate-
nations by forming all pairs in O(n2 and using a frequency array for digits (0 – 9), we check
if each digit exists at least once in each concatenation formed for every pair.
C++
1468
Chapter 236. Number of pairs with Pandigital Concatenation
#include <bits/stdc++.h>
using namespace std;
// Checks if a given
// string is Pandigital
bool isPanDigital(string s)
{
bool digits[10] = {false};
for (int i = 0; i < s.length(); i++)
digits[s[i] - '0'] = true;
// digit i is not present
// thus not pandigital
for (int i = 0; i <= 9; i++)
if (digits[i] == false)
return false;
return true;
}
// Returns number of pairs
// of strings resulting in
// Pandigital Concatenations
int countPandigitalPairs(vector<string> &v)
{
// iterate over all
// pair of strings
int pairs = 0;
for (int i = 0; i < v.size(); i++)
for (int j = i + 1; j < v.size(); j++)
if (isPanDigital(v[i] + v[j]))
pairs++;
return pairs;
}
// Driver code
int main()
{
vector<string> v = {"123567", "098234",
"14765", "19804"};
cout << countPandigitalPairs(v) << endl;
return 0;
}
Java
1469
Chapter 236. Number of pairs with Pandigital Concatenation
// of two strings.
import java.io.*;
import java.util.*;
class GFG
{
static ArrayList<String> v =
new ArrayList<String>();
// Checks if a given
// string is Pandigital
static int isPanDigital(String s)
{
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++)
digits[s.charAt(i) -
(int)'0'] = 1;
// digit i is not present
// thus not pandigital
for (int i = 0; i <= 9; i++)
if (digits[i] == 0)
return 0;
return 1;
}
// Returns number of pairs
// of strings resulting in
// Pandigital Concatenations
static int countPandigitalPairs()
{
// iterate over all
// pair of strings
int pairs = 0;
for (int i = 0; i < v.size(); i++)
for (int j = i + 1;
j < v.size(); j++)
if (isPanDigital(v.get(i) +
v.get(j)) == 1)
pairs++;
return pairs;
}
// Driver code
public static void main(String args[])
{
1470
Chapter 236. Number of pairs with Pandigital Concatenation
v.add("123567");
v.add("098234");
v.add("14765");
v.add("19804");
System.out.print(countPandigitalPairs());
}
}
// This code is contributed
// by Manish Shaw(manishshaw1)
Python3
1471
Chapter 236. Number of pairs with Pandigital Concatenation
if (isPanDigital(v[i] +
v[j])) :
pairs = pairs + 1
return pairs
# Driver code
v = ["123567", "098234",
"14765", "19804"]
print (countPandigitalPairs(v))
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
1472
Chapter 236. Number of pairs with Pandigital Concatenation
int pairs = 0;
for (int i = 0; i < v.Count; i++)
for (int j = i + 1; j < v.Count; j++)
if (isPanDigital(v[i] + v[j]) == 1)
pairs++;
return pairs;
}
// Driver code
static void Main()
{
List<string> v = new List<string>{"123567", "098234",
"14765", "19804"};
Console.WriteLine(countPandigitalPairs(ref v));
}
}
// This code is contributed
// by Manish Shaw(manishshaw1)
PHP
<?php
// PHP program to find all
// Pandigital concatenations
// of two strings.
// Checks if a given
// $is Pandigital
function isPanDigital($s)
{
$digits = array();
$digits = array_fill(0, 10, false);
for ($i = 0; $i < strlen($s); $i++)
$digits[ord($s[$i]) -
ord('0')] = true;
// digit i is not present
// thus not pandigital
for ($i = 0; $i <= 9; $i++)
if ($digits[$i] == false)
return false;
return true;
}
// Returns number of pairs
1473
Chapter 236. Number of pairs with Pandigital Concatenation
Output:
Method 2 (Efficient):
Now we look for something better than the brute-force discussed above. Careful analysis
suggests that, for every digit 0 – 9 to be present we have a mask as 1111111111 (i.e. all
numbers 0-9 exist in the array of numbers
Digits - 0 1 2 3 4 5 6 7 8 9
| | | | | | | | | |
Mask - 1 1 1 1 1 1 1 1 1 1
1474
Chapter 236. Number of pairs with Pandigital Concatenation
So now the approach is to represent every string as a mask of 10 bits where the ith bit is set
if the ith digit exists in the string.
The approach though may look complete is still not efficient as we still have to iterate over
all pairs and check if the OR of these two strings result in the mask of a valid Pandigital
Concatenation.
If we analyze the possible masks of all possible strings we can understand that every single
string would be only comprised of digits 0 – 9, so every number can at max contain all digits
0 to 9 at least once thus the mask of such a number would be 1111111111 (1023 in decimal).
Thus in decimal system all masks exits in (0 – 1023].
Now we just have to maintain a frequency array to store the number of times a mask exists
in the array of strings.
Let two masks be i and j with frequencies freqi and freqj respectively,
If (i OR j) = Maskpandigital concatenation
Then,
Number of Pairs = freqi * freqj
C++
1475
Chapter 236. Number of pairs with Pandigital Concatenation
1476
Chapter 236. Number of pairs with Pandigital Concatenation
Output:
Complexity : O(N * |s| + 1023 * 1023) where |s| gives length of strings in the array
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/number-pairs-pandigital-concatenation/
1477
Chapter 237
Naive Approach: A naive approach is to run three nested loops, the first runs from 0 to
n, second from i+1 to n, and the last one from j+1 to n to get the unique triplets. Calculate
the XOR of ai , aj , ak , check if it equals to 0, if so, then increase the count.
Time Complexity : O(n3 )
Efficient Approach: An efficient approach is to use one of the properties of XOR that
XOR of two same numbers gives 0. So we need to calculate XOR of unique pairs only, and
if the calculated XOR is one of the array element, then we get the triplet whose XOR is 0.
Given below are the steps for counting the number of unique triplets:
Below is the complete algorithm of this approach:
1478
Chapter 237. Number of unique triplets whose XOR is zero
C++
1479
Chapter 237. Number of unique triplets whose XOR is zero
}
// Driver code to test above function
int main()
{
int a[] = {1, 3, 5, 10, 14, 15};
int n = sizeof(a) / sizeof(a[0]);
cout << countTriplets(a, n);
return 0;
}
Java
1480
Chapter 237. Number of unique triplets whose XOR is zero
// if xr of two numbers
// is present, then
// increase the count
if (s.contains(xr) &&
xr != a[i] && xr != a[j])
count++;
}
}
// returns answer
return count / 3;
}
// Driver code
public static void main(String srgs[])
{
int []a = {1, 3, 5,
10, 14, 15};
int n = a.length;
System.out.print(countTriplets(a, n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
C#
// C# program to count
// the number of unique
// triplets whose XOR is 0
using System;
using System.Collections.Generic;
class GFG
{
// function to count the
// number of unique triplets
// whose xor is 0
static int countTriplets(int []a,
int n)
{
// To store values
// that are present
List<int> s = new List<int>();
for (int i = 0; i < n; i++)
s.Add(a[i]);
1481
Chapter 237. Number of unique triplets whose XOR is zero
// stores the count
// of unique triplets
int count = 0;
// traverse for all i,
// j pairs such that j>i
for (int i = 0; i < n; i++)
{
for (int j = i + 1;
j < n; j++)
{
// xor of a[i] and a[j]
int xr = a[i] ^ a[j];
// if xr of two numbers
// is present, then
// increase the count
if (s.Exists(item => item == xr) &&
xr != a[i] && xr != a[j])
count++;
}
}
// returns answer
return count / 3;
}
// Driver code
static void Main()
{
int []a = new int[]{1, 3, 5,
10, 14, 15};
int n = a.Length;
Console.Write(countTriplets(a, n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
1482
Chapter 237. Number of unique triplets whose XOR is zero
Source
https://www.geeksforgeeks.org/number-unique-triplets-whose-xor-zero/
1483
Chapter 238
Number whose XOR sum with given array is a given number k - GeeksforGeeks
Given an array of N numbers and a number K. The task is to insert a number in the given
array such that the bitwise XOR of all the elements in the new array equals the given input
K.
Examples:
Input:
a = {1, 2, 3, 4, 5}, k = 10
Output: 11
Explanation: 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 11 = 10
Approach: The basic idea is to use the simple XOR property, i.e. if X ^ Y = Z then X ^
Z = Y. Let’s suppose the number to be inserted in array be X such that (A[0] ^ A[1] ^ … ^
A[n – 1]) ^ X = k. Thus, to find X we can use the relation (A[0] ^ A[1] ^ … ^ A[n – 1]) ^ k
= X.
Below is the implementation of above approach.
1484
Chapter 238. Number whose XOR sum with given array is a given number k
Java
1485
Chapter 238. Number whose XOR sum with given array is a given number k
return ans;
}
// Driver Code to test above function
public static void main (String[] args)
{
int A[] = { 1, 2, 3, 4, 5 };
int n =A.length;
int k = 10;
System.out.println(
findEletobeInserted(A, n, k)
+ " has to be inserted in "
+ "the given array to make"
+ " xor sum of " + k);
}
}
// This code is contributed by anuj_67.
C#
1486
Chapter 238. Number whose XOR sum with given array is a given number k
int []A = { 1, 2, 3, 4, 5 };
int n =A.Length;
int k = 10;
Console.WriteLine(
findEletobeInserted(A, n, k)
+ " has to be inserted in "
+ "the given array to make"
+ " xor sum of " + k);
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to find the number
// whose XOR sum with given array is
// equal to a given number k
// This function returns the number to
// be inserted in the given array
function findEletobeInserted($A, $n, $k)
{
// initialise the answer with k
$ans = $k;
for ( $i = 0; $i < $n; $i++)
// XOR of all elements
// in the array
$ans ^= $A[$i];
return $ans;
}
// Driver Code
$A = array(1, 2, 3, 4, 5);
$n = count($A);
$k = 10;
echo findEletobeInserted($A, $n, $k) ;
echo " has to be inserted";
echo " in the given array to make xor sum of ";
echo $k , "\n";
// This code is contributed by anuj_67.
?>
1487
Chapter 238. Number whose XOR sum with given array is a given number k
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/number-whose-xor-sum-given-array-given-number-k/
1488
Chapter 239
Number whose sum of XOR with given array range is maximum - GeeksforGeeks
You are given a sequence of N integers and Q queries. In each query, you are given two
parameters L and R. You have to find the smallest integer X such that 0 <= X < 2^31 and
the sum of XOR of x with all elements is range [L, R] is maximum possible.
Examples :
Approach: The binary representation of each element and X, we can observe that each bit
is independent and the problem can be solved by iterating over each bit. Now basically for
each bit we need to count the number of 1’s and 0’s in the given range, if the number of 1’s
are more then you have to set that bit of X to 0 so that the sum is maximum after xor with
X else if number of 0’s are more then you have to set that bit of X to 1. If the number of
1’s and 0’s are equal then we can set that bit of X to any one of 1 or 0 because it will not
affect the sum, but we have to minimize the value of X so we will take that bit 0.
Now, to optimize the solution we can pre-calculate the count of 1’s at each bit position of
the numbers up to that position by making a prefix array this will take O(n) time. Now for
1489
Chapter 239. Number whose sum of XOR with given array range is maximum
each query number of 1’s will be the number of 1’s up to Rth position – number of 1’s up
to (L-1)th position.
C++
1490
Chapter 239. Number whose sum of XOR with given array range is maximum
Java
1491
Chapter 239. Number whose sum of XOR with given array range is maximum
1492
Chapter 239. Number whose sum of XOR with given array range is maximum
Python3
1493
Chapter 239. Number whose sum of XOR with given array range is maximum
1494
Chapter 239. Number whose sum of XOR with given array range is maximum
C#
1495
Chapter 239. Number whose sum of XOR with given array range is maximum
// If j-th bit of a number is set then
// add one to previously counted 1's
if ((a & x) != 0)
one[i, j] = 1 + one[i - 1, j];
else
one[i,j] = one[i - 1, j];
}
}
}
// Function to find X
static int Solve(int L, int R)
{
int l = L, r = R;
int tot_bits = r - l + 1;
// Initially taking maximum
// value all bits 1
int X = MAX;
// Iterating over each bit
for (int i = 0; i < 31; i++)
{
// get 1's at ith bit between the
// range L-R by subtracting 1's till
// Rth number - 1's till L-1th number
int x = one[r, i] - one[l - 1, i];
// If 1's are more than or
// equal to 0's then unset
// the ith bit from answer
if (x >= tot_bits - x)
{
int ith_bit = (int)Math.Pow(2, i);
// Set ith bit to 0 by doing
// Xor with 1
X = X ^ ith_bit;
}
}
return X;
}
// Driver Code
public static void Main()
{
1496
Chapter 239. Number whose sum of XOR with given array range is maximum
// Taking inputs
int n = 5, q = 3;
int []A = {210, 11, 48, 22, 133};
int []L = {1, 4, 2};
int []R = {3, 14, 4};
make_prefix(A, n);
for (int j = 0; j < q; j++)
Console.WriteLine(Solve(L[j], R[j]));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
error_reporting(0);
// PHP program to find smallest integer X
// such that sum of its XOR with range is
// maximum.
$one = array();
$MAX = 2147483647;
// Function to make prefix array
// which counts 1's of each bit
// up to that number
function make_prefix($A, $n)
{
global $one, $MAX;
for ($j = 0; $j < 32; $j++)
$one[0][$j] = 0;
// Making a prefix array which
// sums number of 1's up to
// that position
for ($i = 1; $i <= $n; $i++)
{
$a = $A[$i - 1];
for ($j = 0; $j < 32; $j++)
{
$x = pow(2, $j);
1497
Chapter 239. Number whose sum of XOR with given array range is maximum
1498
Chapter 239. Number whose sum of XOR with given array range is maximum
Output :
2147483629
2147483647
2147483629
Source
https://www.geeksforgeeks.org/number-whose-sum-of-xor-with-given-array-range-is-maximum/
1499
Chapter 240
Number with set bits only between L-th and R-th index - GeeksforGeeks
Given L and R. The task is to find the number in whose binary representation all bits
between the L-th and R-th index are set and the rest of the bits are unset. The binary
representation is of 32 bits.
Examples:
Input: L = 2, R = 5
Output: 60
Explanation: The binary representation is
0..0111100 => 60
Input: L = 1, R = 3
Output: 14
Explanation: The binary representation is
0..01110 => 14
Naive Approach: The naive approach to find the number is to iterate from i = L to i =
R and calculate the addition of all the powers of 2i .
Below program illustrate the naive approach:
C++
1500
Chapter 240. Number with set bits only between L-th and R-th index
// Function to return the integer
// with all the bits set in range L-R
int getInteger(int L, int R)
{
int number = 0;
// iterate from L to R
// and add all powers of 2
for (int i = L; i <= R; i++)
number += pow(2, i);
return number;
}
// Driver Code
int main()
{
int L = 2, R = 5;
cout << getInteger(L, R);
return 0;
}
Java
1501
Chapter 240. Number with set bits only between L-th and R-th index
}
// Driver Code
public static void main (String[] args)
{
int L = 2, R = 5;
System.out.println(getInteger(L, R));
}
}
// This code is contributed by anuj_67..
C#
1502
Chapter 240. Number with set bits only between L-th and R-th index
PHP
<?php
// PHP program to print
// the integer with all
// the bits set in range
// L-R Naive Approach
// Function to return the
// integer with all the
// bits set in range L-R
function getInteger($L, $R)
{
$number = 0;
// iterate from L to R
// and add all powers of 2
for ($i = $L; $i <= $R; $i++)
$number += pow(2, $i);
return $number;
}
// Driver Code
$L = 2;
$R = 5;
echo getInteger($L, $R);
// This code is contributed
// by shiv_bhakt.
?>
Output:
60
An efficient approach is to compute the number with all (R) set bits from right and
subtract the number with all (L-1) bits set from right to get the required number.
1. Compute the number which has all R set bits from the right using the below formula.
(1 << (R+1)) - 1.
2. Subtract the number which has all (L-1) set bits from the right.
(1<<L) - 1
1503
Chapter 240. Number with set bits only between L-th and R-th index
(1<<(R+1))-(1<<L)
C++
Java
1504
Chapter 240. Number with set bits only between L-th and R-th index
Python3
C#
// C# program to print
// the integer with all
// the bits set in range
// L-R Efficient Approach
using System;
class GFG
1505
Chapter 240. Number with set bits only between L-th and R-th index
{
// Function to return the
// integer with all the
// bits set in range L-R
static int setbitsfromLtoR(int L,
int R)
{
return (1 << (R + 1)) -
(1 << L);
}
// Driver Code
public static void Main ()
{
int L = 2, R = 5;
Console.WriteLine(setbitsfromLtoR(L, R));
}
}
// This code is contributed
// by shiv_bhakt.
PHP
<?php
// PHP program to print
// the integer with all
// the bits set in range
// L-R Efficient Approach
// Function to return the
// integer with all the
// bits set in range L-R
function setbitsfromLtoR($L, $R)
{
return (1 << ($R + 1)) -
(1 << $L);
}
// Driver Code
$L = 2;
$R = 5;
echo setbitsfromLtoR($L, $R);
// This code is contributed
// by shiv_bhakt.
?>
1506
Chapter 240. Number with set bits only between L-th and R-th index
Output:
60
Source
https://www.geeksforgeeks.org/number-with-set-bits-only-between-l-th-and-r-th-index/
1507
Chapter 241
Input : N = 3
Output : 1
0 is the only number in [0, 3]
that satisfies given property.
(0 + 3) = (0 | 3)
Input : 10
Output : 4
(0 + 10) = (0 | 10) (Both are 10)
(1 + 10) = (1 | 10) (Both are 11)
(4 + 10) = (4 | 10) (Both are 14)
(5 + 10) = (5 | 10) (Both are 15)
A simple solution is to traverse all numbers from 0 to N and do bitwise OR and SUM
with N, if both are equal increment counter.
Time complexity = O(N).
An efficient solution is to follow following steps.
1. Find count of zero bit in N.
2. Return pow(2,count).
The idea is based on the fact that bitwise OR and sum of a number x with N are equal, if
and only if
bitwise AND of x with N will is 0
1508
Chapter 241. Numbers whose bitwise OR and sum with N are equal
C++
1509
Chapter 241. Numbers whose bitwise OR and sum with N are equal
}
// Driver code
int main()
{
int N = 10;
cout << CountORandSumEqual(N);
return 0;
}
Java
1510
Chapter 241. Numbers whose bitwise OR and sum with N are equal
int N = 10;
System.out.print(CountORandSumEqual(N));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
1511
Chapter 241. Numbers whose bitwise OR and sum with N are equal
using System;
class GFG
{
// Function to find total
// 0 bit in a number
static int CountZeroBit(int n)
{
int count = 0;
while(n>0)
{
if (n%2!=0)
count++;
n >>= 1;
}
return count;
}
// Function to find Count of non-negative
// numbers less than or equal to N, whose
// bitwise OR and SUM with N are equal.
static int CountORandSumEqual(int N )
{
// count number of zero bit in N
int count = CountZeroBit(N);
// power of 2 to count
return (1 << count);
}
//Driver code
public static void Main()
{
int N = 10;
Console.Write(CountORandSumEqual(N));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to count
// numbers whose bitwise
// OR and sum with N are equal
1512
Chapter 241. Numbers whose bitwise OR and sum with N are equal
// Function to find total
// 0 bit in a number
function CountZeroBit($n)
{
$count = 0;
while($n)
{
if (!($n & 1))
$count++;
$n >>= 1;
}
return $count;
}
// Function to find Count of
// non-negative numbers less
// than or equal to N, whose
// bitwise OR and SUM with N
// are equal.
function CountORandSumEqual($N )
{
// count number of
// zero bit in N
$count = CountZeroBit($N);
// power of 2 to count
return (1 << $count);
}
// Driver code
$N = 10;
echo CountORandSumEqual($N);
// This code is contributed by Ajit
?>
Output :
Improved By : jit_t
1513
Chapter 241. Numbers whose bitwise OR and sum with N are equal
Source
https://www.geeksforgeeks.org/numbers-whose-bitwise-sum-n-equal/
1514
Chapter 242
Input : 11
Output : 8
Input : 20
Output : 4
1515
Chapter 242. Odd numbers in N-th row of Pascal’s Triangle
Approach : It appears the answer is always a power of 2. In fact, the following theorem
exists :
THEOREM : The number of odd entries in row N of Pascal’s Triangle is 2 raised to the
number of 1’s in the binary expansion of N.
Example: Since 83 = 64 + 16 + 2 + 1 has binary expansion (1010011), then row 83 has
pow(2, 4) = 16 odd numbers.
Below is the implementation of above approach :
C++
// CPP code to find the count of odd numbers
// in n-th row of Pascal's Triangle
#include <bits/stdc++.h>
using namespace std ;
/* Function to get no of set
bits in binary representation
of positive integer n */
int countSetBits(int n)
1516
Chapter 242. Odd numbers in N-th row of Pascal’s Triangle
{
unsigned int count = 0;
while (n)
{
count += n & 1;
n >>= 1;
}
return count;
}
int countOfOddsPascal(int n)
{
// Count number of 1's in binary
// representation of n.
int c = countSetBits(n);
// Number of odd numbers in n-th
// row is 2 raised to power the count.
return pow(2, c);
}
// Driver code
int main()
{
int n = 20;
cout << countOfOddsPascal(n) ;
return 0;
}
Java
1517
Chapter 242. Odd numbers in N-th row of Pascal’s Triangle
n >>= 1;
}
return (int)count;
}
static int countOfOddsPascal(int n)
{
// Count number of 1's in binary
// representation of n.
int c = countSetBits(n);
// Number of odd numbers in n-th
// row is 2 raised to power the
// count.
return (int)Math.pow(2, c);
}
// Driver code
public static void main (String[] args)
{
int n = 20;
System.out.println(
countOfOddsPascal(n));
}
}
// This code is contributed by anuj_67.
Python3
1518
Chapter 242. Odd numbers in N-th row of Pascal’s Triangle
# Count number of 1's in binary
# representation of n.
c = countSetBits(n)
# Number of odd numbers in n-th
# row is 2 raised to power the count.
return pow(2, c)
# Driver Program
n = 20
print(countOfOddPascal(n))
# This code is contributed by Shrikant13
C#
1519
Chapter 242. Odd numbers in N-th row of Pascal’s Triangle
}
// Driver code
public static void Main ()
{
int n = 20;
Console.WriteLine(
countOfOddsPascal(n)) ;
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP code to find the
// count of odd numbers
// in n-th row of Pascal's
// Triangle
/* Function to get no of set
bits in binary representation
of positive integer n */
function countSetBits($n)
{
$count = 0;
while ($n)
{
$count += $n & 1;
$n >>= 1;
}
return $count;
}
function countOfOddsPascal($n)
{
// Count number of 1's in binary
// representation of n.
$c = countSetBits($n);
// Number of odd numbers in n-th
// row is 2 raised to power the count.
return pow(2, $c);
}
1520
Chapter 242. Odd numbers in N-th row of Pascal’s Triangle
Output:
Source
https://www.geeksforgeeks.org/odd-numbers-in-n-th-row-of-pascals-triangle/
1521
Chapter 243
Odious number
Input : 16
Output : Odious Number
Explanation: Binary expansion of 16 = 10000,
having number of 1s =1 i.e odd.
Input : 23
Output : Not odious number
Explanation: Binary expansion of 23 is 10111,
the number of 1s in this is 4 i.e even.
C++
1522
Chapter 243. Odious number
Java
1523
Chapter 243. Odious number
int count = 0;
while (n!=0)
{
n &= (n-1) ;
count++;
}
return count;
}
// Check if number is odious or not
static boolean checkOdious(int n)
{
return (countSetBits(n) % 2 == 1);
}
// Driver Code
public static void main(String args[])
{
int num = 32;
if (checkOdious(num))
System.out.println("Yes");
else
System.out.println("No");
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3
1524
Chapter 243. Odious number
def checkOdious(n) :
return (countSetBits(n) % 2 == 1)
# Driver Code
num = 32
if (checkOdious(num)) :
print("Yes")
else :
print("No")
# This code is contributed by Nikita Tiwari.
C#
1525
Chapter 243. Odious number
PHP
<?php
// PHP program to check if a number
// is Odious Number or not
// Function to get no of
// set bits in binary
function countSetBits($n)
{
$count = 0;
while ($n)
{
$n &= ($n - 1) ;
$count++;
}
return $count;
}
// Check if number is odious or not
function checkOdious($n)
{
return (countSetBits($n) % 2 == 1);
}
// Driver Code
$num = 32;
if (checkOdious($num))
echo "Yes";
else
echo "No";
// This code is contributed by mits
?>
Output :
Yes
1526
Chapter 243. Odious number
Source
https://www.geeksforgeeks.org/odious-number/
1527
Chapter 244
Operators in C | Set 2
(Relational and Logical
Operators)
• ‘==’ operator checks whether the two given operands are equal or not. If so, it returns
true. Otherwise it returns false. For example, 5==5 will return true.
• ‘!=’ operator checks whether the two given operands are equal or not. If not, it
returns true. Otherwise it returns false. It is the exact boolean complement of the
‘==’ operator. For example, 5!=5 will return false.
• ‘>’ operator checks whether the first operand is greater than the second operand. If
so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
• ‘<‘ operator checks whether the first operand is lesser than the second operand. If so,
it returns true. Otherwise it returns false. For example, 6<5 will return false.
• ‘>=’ operator checks whether the first operand is greater than or equal to the second
operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will
return true.
• ‘<=’ operator checks whether the first operand is lesser than or equal to the second
operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will
also return true.
1528
Chapter 244. Operators in C | Set 2 (Relational and Logical Operators)
int main()
{
int a=10, b=4;
// relational operators
// greater than example
if (a > b)
printf("a is greater than b\n");
else printf("a is less than or equal to b\n");
// greater than equal to
if (a >= b)
printf("a is greater than or equal to b\n");
else printf("a is lesser than b\n");
// less than example
if (a < b)
printf("a is less than b\n");
else printf("a is greater than or equal to b\n");
// lesser than equal to
if (a <= b)
printf("a is lesser than or equal to b\n");
else printf("a is greater than b\n");
// equal to
if (a == b)
printf("a is equal to b\n");
else printf("a and b are not equal\n");
// not equal to
if (a != b)
printf("a is not equal to b\n");
else printf("a is equal b\n");
return 0;
}
Output:
a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b
1529
Chapter 244. Operators in C | Set 2 (Relational and Logical Operators)
Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evalua-
tion of the original condition in consideration. They are described below:
• Logical AND: The ‘&&’ operator returns true when both the conditions in consid-
eration are satisfied. Otherwise it returns false. For example, a && b returns true
when both a and b are true (i.e. non-zero).
• Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in
consideration is satisfied. Otherwise it returns false. For example, a || b returns true
if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b
are true.
• Logical NOT: The ‘!’ operator returns true the condition in consideration is not
satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when
a=0.
Output:
1530
Chapter 244. Operators in C | Set 2 (Relational and Logical Operators)
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a=10, b=4;
bool res = ((a == b) && printf("GeeksQuiz"));
return 0;
}
But below program prints “GeeksQuiz” as first operand of logical AND is true.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a=10, b=4;
bool res = ((a != b) && printf("GeeksQuiz"));
return 0;
}
In case of logical OR, the second operand is not evaluated if first operand is true. For
example, program 1 below doesn’t print “GeeksQuiz” as the first operand of logical OR
itself is true.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a=10, b=4;
bool res = ((a != b) || printf("GeeksQuiz"));
return 0;
}
#include <stdio.h>
#include <stdbool.h>
1531
Chapter 244. Operators in C | Set 2 (Relational and Logical Operators)
int main()
{
int a=10, b=4;
bool res = ((a == b) || printf("GeeksQuiz"));
return 0;
}
Quiz on Operators in C
This article is contributed by Ayush Jaggi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/operators-in-c-set-2-relational-and-logical-operators/
1532
Chapter 245
1533
Chapter 245. Optimization Techniques | Set 1 (Modulus)
Modulus operation over exact powers of 2 is simple and faster bitwise ANDing. This is the
reason, programmers usually make buffer length as powers of 2.
Note that the technique will work only for divisors that are powers of 2.
An Example:
Implementation of circular queue (ring buffer) using an array. Omitting one position in
the circular buffer implementation can make it easy to distinguish between full and empty
conditions. When the buffer reaches SIZE-1, it needs to wrap back to initial position. The
wrap back operation can be simple AND operation if the buffer size is power of 2. If we use
any other size, we would need to use modulus operation.
Note:
Per experts comments, premature optimization is an evil. The optimization techniques
provided are to fine tune your code after finalizing design strategy, algorithm, data structures
and implementation. We recommend to avoid them at the start of code development. Code
readability is key for maintenance.
Thanks to Venki for writing the above article. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/optimization-techniques-set-1-modulus/
1534
Chapter 246
1535
Chapter 246. Pairs of complete strings in two sets of strings
// strings.
#include<iostream>
using namespace std;
// Returns count of complete pairs from set[0..n-1]
// and set2[0..m-1]
int countCompletePairs(string set1[], string set2[],
int n, int m)
{
int result = 0;
// Consider all pairs of both strings
for (int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
{
// Create a concatenation of current pair
string concat = set1[i] + set2[j];
// Compute frequencies of all characters
// in the concatenated string.
int frequency[26] = {0};
for (int k=0; k<concat.length(); k++)
frequency[concat[k] - 'a']++;
// If frequency of any character is not
// greater than 0, then this pair is not
// complete.
int i;
for (i=0; i<26; i++)
if (frequency[i] < 1)
break;
if (i == 26)
result++;
}
}
return result;
}
// Driver code
int main()
{
string set1[] = {"abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc"};
string set2[] = {"ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz"};
1536
Chapter 246. Pairs of complete strings in two sets of strings
int n = sizeof(set1)/sizeof(set1[0]);
int m = sizeof(set2)/sizeof(set2[0]);
cout << countCompletePairs(set1, set2, n, m);
return 0;
}
Output:
1537
Chapter 246. Pairs of complete strings in two sets of strings
1538
Chapter 246. Pairs of complete strings in two sets of strings
};
int n = sizeof(set1)/sizeof(set1[0]);
int m = sizeof(set2)/sizeof(set2[0]);
cout << countCompletePairs(set1, set2, n, m);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/pairs-of-complete-strings-in-two-sets-of-strings/
1539
Chapter 247
1540
Chapter 247. Pairs whose concatenation contain all digits
cnt[mask]++;
}
A pair of numbers will have all the digit from 0 to 9 if every bits from 0 to 9 is set in the
bitwise OR of maskof both the number, i.e if it’s equal to (1111111111)2</sub) = (1023)10
Now, we will iterate over all pairs of masks whose biwise OR is equal to 1023 and add the
number of ways.
Below is C++ implementation of this approach:
1541
Chapter 247. Pairs whose concatenation contain all digits
Output:
Source
https://www.geeksforgeeks.org/pairs-whose-concatenation-contain-digits/
1542
Chapter 248
Pernicious number
C++
1543
Chapter 248. Pernicious number
bool isPrime(int x)
{
if (x < 2)
return false;
for (int i = 2; i < x; i++) {
if (x % i == 0)
return false;
}
return true;
}
// Prints first n Pernicious numbers
void printPernicious(int n)
{
for (int i=1,count=0; count<n; i++) {
// "__builtin_popcount(i)" count no
// of ones in binary representation
if (isPrime(__builtin_popcount(i))) {
cout << i << " ";
count++;
}
}
}
int main()
{
int n = 25;
printPernicious(n);
return 0;
}
Java
1544
Chapter 248. Pernicious number
n &= (n - 1) ;
count++;
}
return count;
}
// function to check prime number
static boolean isPrime(int x)
{
if (x < 2)
return false;
for (int i = 2; i < x; i++) {
if (x % i == 0)
return false;
}
return true;
}
// Prints first n Pernicious numbers
static void printPernicious(int n)
{
for (int i=1,count=0; count<n; i++) {
if (isPrime(countSetBits(i))) {
System.out.print( i + " ");
count++;
}
}
}
// Driver Code
public static void main (String[] args) {
int n = 25;
printPernicious(n);
}
}
// This code is contributed by Ansu Kumari
Python3
1545
Chapter 248. Pernicious number
if x < 2:
return False
for i in range(2, x):
if not x % i:
return False
return True
# Prints first n Pernicious
# numbers
def printPernicious(n):
i, count = 1, 0
while count < n:
# "bin(i).count('1')" count
# no of ones in binary
# representation
if (isPrime(bin(i).count('1'))):
print(i, end=' ')
count += 1
i += 1
# Driver Code
n = 25
printPernicious(n)
# This code is contributed by Ansu Kumari
C#
1546
Chapter 248. Pernicious number
{
n &= (n - 1) ;
count++;
}
return count;
}
// function to check prime number
static bool isPrime(int x)
{
if (x < 2)
return false;
for (int i = 2; i < x; i++) {
if (x % i == 0)
return false;
}
return true;
}
// Prints first n Pernicious numbers
static void printPernicious(int n)
{
for (int i=1,count=0; count<n; i++) {
if (isPrime(countSetBits(i))) {
Console.Write( i + " ");
count++;
}
}
}
// Driver Code
public static void Main ()
{
int n = 25;
printPernicious(n);
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to print first
// n pernicious numbers
1547
Chapter 248. Pernicious number
1548
Chapter 248. Pernicious number
// This code is contributed by mits
?>
Output :
3 5 6 7 9 10 11 12 13 14 17 18 19 20 21 22 24 25 26 28 31 33 34 35 36
References :
Wiki
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/pernicious-number/
1549
Chapter 249
Position of rightmost bit with first carry in sum of two binary - GeeksforGeeks
Given two non-negative integers a and b. The problem is to find the position of the rightmost
bit where a carry is generated in the binary addition of a and b.
Examples:
Input : a = 10, b = 2
Output : 2
(10)10 = (1010)2
(2)10 = (10)2.
1010
+ 10
As highlighted, 1st carry bit from the right
will be generated at position '2'.
Input : a = 10, b = 5
Output : 0
'0' as no carry bit will be generated.
CPP
1550
Chapter 249. Position of rightmost bit with first carry in sum of two binary
Java
1551
Chapter 249. Position of rightmost bit with first carry in sum of two binary
Python3
C#
1552
Chapter 249. Position of rightmost bit with first carry in sum of two binary
Output:
Source
https://www.geeksforgeeks.org/position-rightmost-bit-first-carry-sum-two-binary/
1553
Chapter 250
Input : m = 10, n = 9
Output : 3
(10)10 = (1010)2
(9)10 = (1001)2
It can be seen that the 3rd bit
from the right is same.
Input : m = 16, n = 7
Output : 4
(16)10 = (10000)2
(7)10 = (111)2, can also be written as
= (00111)2
It can be seen that the 4th bit
from the right is same.
Approach: Get the bitwise xor of m and n. Let it be xor_value = m ^ n. Now, get the
position of rightmost unset bit in xor_value.
Explanation: The bitwise xor operation produces a number which has unset bits only at
the positions where the bits of m and n are same. Thus, the position of rightmost unset bit
in xor_value gives the position of rightmost same bit.
C++
1554
Chapter 250. Position of rightmost common bit in two numbers
Java
1555
Chapter 250. Position of rightmost common bit in two numbers
Python3
C#
1556
Chapter 250. Position of rightmost common bit in two numbers
PHP
<?php
// PHP implementation to
// find the position
// of rightmost same bit
// Function to find the position of
// rightmost set bit in 'n'
function getRightMostSetBit($n)
{
return log($n & -$n) + 1;
}
// Function to find the position of
// rightmost same bit in the
1557
Chapter 250. Position of rightmost common bit in two numbers
Output:
Position = 4
Improved By : vt_m
Source
https://www.geeksforgeeks.org/position-rightmost-common-bit-two-numbers/
1558
Chapter 251
Input : m = 11, n = 9
Output : 2
(11)10 = (1011)2
(9)10 = (1001)2
It can be seen that 2nd bit from
the right is different
Input : m = 52, n = 4
Output : 5
(52)10 = (110100)2
(4)10 = (100)2, can also be written as
= (000100)2
It can be seen that 5th bit from
the right is different
Approach: Get the bitwise xor of m and n. Let it be xor_value = m ^ n. Now, find the
position of rightmost set bit in xor_value.
Explanation: The bitwise xor operation produces a number which has set bits only at
the positions where the bits of m and n differ. Thus, the position of rightmost set bit in
xor_value gives the position of rightmost different bit.
C++
1559
Chapter 251. Position of rightmost different bit
Java
1560
Chapter 251. Position of rightmost different bit
{
// position of rightmost different bit
return getRightMostSetBit(m ^ n);
}
// Driver code
public static void main(String arg[])
{
int m = 52, n = 4;
System.out.print("Position = " +
posOfRightMostDiffBit(m, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python implementation
# to find the position
# of rightmost different bit
import math
# Function to find the position of
# rightmost set bit in 'n'
def getRightMostSetBit(n):
return math.log2(n & -n) + 1
# Function to find the position of
# rightmost different bit in the
# binary representations of 'm' and 'n'
def posOfRightMostDiffBit(m, n):
# position of rightmost different
# bit
return getRightMostSetBit(m ^ n)
# Driver code
m = 52
n = 4
print("position = ", int(posOfRightMostDiffBit(m, n)))
# This code is contributed
# by Anant Agarwal.
1561
Chapter 251. Position of rightmost different bit
C#
PHP
<?php
// PHP implementation to
// find the position of
// rightmost different bit
// Function to find the position
// of rightmost set bit in 'n'
function getRightMostSetBit($n)
{
1562
Chapter 251. Position of rightmost different bit
Output:
1563
Chapter 251. Position of rightmost different bit
int m = 52, n = 4;
cout <<"Position = " <<
posOfRightMostDiffBit(m, n);
return 0;
}
PHP
<?php
// PHP implementation to find the
// position of rightmost different
// bit in two number.
// function to find rightmost
// different bit in two numbers.
function posOfRightMostDiffBit($m, $n)
{
$t = floor(log($m ^ $n, 2));
return $t;
}
// Driver code
$m = 52;
$n = 4;
echo "Position = " ,
posOfRightMostDiffBit($m, $n);
// This code is contributed by ajit
?>
Output :
Position = 5
Source
https://www.geeksforgeeks.org/position-rightmost-different-bit/
1564
Chapter 252
2 Do an bit-wise & with original no, this will return no with the
required one only (00010)
3 Take the log2 of the no, you will get position -1 (1)
4 Add 1 (2)
Program:
#include <math.h>
#include <stdio.h>
1565
Chapter 252. Position of rightmost set bit
unsigned int getFirstSetBitPos(int n)
{
return log2(n & -n) + 1;
}
int main()
{
int n = 12;
printf("%u", getFirstSetBitPos(n));
getchar();
return 0;
}
Java
Python3
1566
Chapter 252. Position of rightmost set bit
print(int(getFirstSetBitPos(n)))
# This code is contributed
# by Anant Agarwal.
C#
PHP
<?php
// PHP Code for Position of
// rightmost set bit
function getFirstSetBitPos($n)
{
return ceil(log(($n& -
$n) + 1, 2));
}
// Driver Code
$n = 12;
echo getFirstSetBitPos($n);
// This code is contributed by m_kit
?>
Output:
1567
Chapter 252. Position of rightmost set bit
Using ffs() function: ffs() function returns the index of first least significant set bit. The
indexing starts in ffs() function from 1.
For example:
n = 12 = 1100
In above example, ffs(n) returns the rightmost set bit index which is 3.
C++
1568
Chapter 252. Position of rightmost set bit
int position = 1;
int m = 1;
while (!(n & m)) {
// left shift
m = m << 1;
position++;
}
return position;
}
// Driver Code
int main()
{
int n = 16;
// function call
cout << PositionRightmostSetbit(n);
return 0;
}
Java
1569
Chapter 252. Position of rightmost set bit
Python3
C#
1570
Chapter 252. Position of rightmost set bit
PHP
<?php
// PHP program to find the
// first rightmost set bit
// using XOR operator
// function to find the
// rightmost set bit
1571
Chapter 252. Position of rightmost set bit
function PositionRightmostSetbit($n)
{
// Position variable initialize
// with 1 m variable is used to
// check the set bit
$position = 1;
$m = 1;
while (!($n & $m))
{
// left shift
$m = $m << 1;
$position++;
}
return $position;
}
// Driver Code
$n = 16;
// function call
echo PositionRightmostSetbit($n);
// This code is contributed by ajit
?>
Output:
#include <iostream>
using namespace std;
#define INT_SIZE 32
int Right_most_setbit(int num)
{
int pos = 1;
// counting the position of first set bit
for (int i = 0; i < INT_SIZE; i++) {
if (!(num & (1 << i)))
pos++;
else
1572
Chapter 252. Position of rightmost set bit
break;
}
return pos;
}
int main()
{
int num = 18;
int pos = Right_most_setbit(num);
cout << pos << endl;
return 0;
}
// This approach has been contributed by @vivek kumar9
Output :
Source
https://www.geeksforgeeks.org/position-of-rightmost-set-bit/
1573
Chapter 253
Input : 71307
Output : 0, 1, 3, 7, 9, 10, 12, 16
Explanation :
71307 = 2^0 + 2^1 + 2^3 + 2^7 +
2^9 + 2^10 + 2^12 + 2^16
Input : 1213
Output : 0, 2, 3, 4, 5, 7, 10
Explanation :
1213 = 2^0 + 2^2 + 2^3 + 2^4 +
2^5 + 2^7 + 2^10
Approach :
Every number can be described in powers of 2.
Example : 29 = 2^0 + 2^2 + 2^3 + 2^4.
2^0 ( exponent of 2 is ‘0’) 0
2^2 ( exponent of 2 is ‘2’) 1
2^3 ( exponent of 2 is ‘3’) 3
2^4 ( exponent of 2 is ‘4’) 4
Convert each number into its binary equivalent by pushing remainder of given number, when
divided by 2 till it is greater than 0, to vector. Now, Iterate through its binary equivalent
and whenever there is set bit, just print the i-th value(iteration number).
Application :
Hamming Code : Hamming Code is an error correcting code which can detect and correct
1574
Chapter 253. Powers of 2 to required sum
one bit error. This pattern is also used in Hamming code error detection where parity bits
store the XOR of numbers on the basis of LSB(Least Significant bit), where numbers are
assigned in blocks and you need to find the blocks where the sum of power of 2 resulting to
given number exists. Below is the image to show the blocks with given numbers.
C++
1575
Chapter 253. Powers of 2 to required sum
v.push_back(x % 2);
x = x / 2;
}
// Displaying the output when
// the bit is '1' in binary
// equivalent of number.
for (int i = 0; i < v.size(); i++)
{
if (v[i] == 1)
{
cout << i;
if (i != v.size() - 1)
cout << ", ";
}
}
cout << endl;
}
// Driver Function
int main()
{
block(71307);
block(1213);
block(29);
block(100);
return 0;
}
Java
1576
Chapter 253. Powers of 2 to required sum
}
// Displaying the output when
// the bit is '1' in binary
// equivalent of number.
for (int i = 0; i < v.size(); i++)
{
if (v.get(i) == 1)
{
System.out.print(i);
if (i != v.size() - 1)
System.out.print( ", ");
}
}
System.out.println();
}
// Driver Code
public static void main(String args[])
{
block(71307);
block(1213);
block(29);
block(100);
}
}
// This code is contributed by Arnab Kundu.
Python3
1577
Chapter 253. Powers of 2 to required sum
C#
1578
Chapter 253. Powers of 2 to required sum
}
}
Console.WriteLine();
}
// Driver Code here
public static void Main()
{
block(71307);
block(1213);
block(29);
block(100);
}
}
// This code is contributed by Ajit.
PHP
<?php
// PHP program to find the
// blocks for given number.
function block($x)
{
$v = array();
// Convert decimal number to
// its binary equivalent
echo 'Blocks for ' .$x.' : ';
while ($x > 0)
{
array_push($v,intval($x % 2));
$x = intval($x / 2);
}
// Displaying the output when
// the bit is '1' in binary
// equivalent of number.
for ($i = 0; $i < sizeof($v); $i++)
{
if ($v[$i] == 1)
{
print $i;
if ($i != sizeof($v) - 1)
1579
Chapter 253. Powers of 2 to required sum
Output:
Source
https://www.geeksforgeeks.org/powers-2-required-sum/
1580
Chapter 254
Input : 14
Output : NO
Storing 14 as a 4 bit number, 14 (1110), its predecessor 13 (1101), its 1’s comple-
ment 1 (0001), 13 and 1 are not same in their binary representation and hence
output is NO.
Input : 8
Output : YES
Storing 8 as a 4 bit number, 8 (1000), its predecessor 7 (0111), its 1’s complement
7 (0111), both its predecessor and its 1’s complement are 7 and hence output is
YES.
Simple Approach: In this approach, we actually calculate the complement of the number.
1. Find binary representation of the number’s predecessor and it’s 1’s complement using
simple decimal to binary representation technique.
2. Compare bit by bit to check whether they are equal or not.
3. If all bits are equal then print YES else print NO.
Time Complexity: O (log n), as binary representation of numbers is getting calculated.
Auxiliary Space: O (1), although auxiliary space is O (1) still some memory spaces are
getting
used to store binary representation of the numbers.
1581
Chapter 254. Previous number same as 1’s complement
Efficient Approach: Only numbers which are powers of 2 have binary representation of
their predecessor and their 1’s complement as same.
1. Check whether a number is power of 2 or not.
2. If a number is power of 2 then print YES else print NO.
C++
Java
1582
Chapter 254. Previous number same as 1’s complement
// Driver code
public static void main(String args[]) {
int n = 14;
if(bit_check(n))
System.out.println ('1');
else
System.out.println('0');
}
}
// This code is contributed by Sam007
C#
PHP
1583
Chapter 254. Previous number same as 1’s complement
<?php
// An efficient PHP program to check
// if binary representations of n's
// predecessor and its 1's complement
// are same.
// Returns true if binary
// representations of n's
// predecessor and it's 1's
// complement are same.
function bit_check($n)
{
if (($n & ($n - 1)) == 0)
return 1;
return 0;
}
// Driver code
$n = 14;
echo bit_check($n);
// This code is contributed by Sam007.
?>
Output:
Source
https://www.geeksforgeeks.org/previous-number-1s-complement/
1584
Chapter 255
Previous smaller integer having one less number of set bits - GeeksforGeeks
Given a positive integer ‘n’ having ‘x’ number of set bits in its binary representation. The
problem is to find the previous smaller integer(greatest integer smaller than n), having (x-1)
number of set bits in its binary representation.
Note: 1 <= n
Examples :
Input : 8
Output : 0
(8)10 = (1000)2
is having 1 set bit.
(0)10 = (0)2
is having 0 set bit and is the previous smaller.
Input : 25
Output : 24
1. Find the position of the rightmost set bit(considering last bit at position 1, second
last bit at position 2 and so on) in the binary representation of n. Let the position be
represented by pos. Refer this post.
2. Turn off or unset the bit at position pos. Refer this post.
C++
1585
Chapter 255. Previous smaller integer having one less number of set bits
Java
1586
Chapter 255. Previous smaller integer having one less number of set bits
// integer
static int previousSmallerInteger(int n)
{
// position of rightmost set bit of n
int pos = getFirstSetBitPos(n);
// turn off or unset the bit at
// position 'pos'
return (n & ~(1 << (pos - 1)));
}
// Driver code
public static void main(String[] args)
{
int n = 25;
System.out.print("Previous smaller Integer ="
+ previousSmallerInteger(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
1587
Chapter 255. Previous smaller integer having one less number of set bits
# Driver code
n = 25
print("Previous small Integer = ",
previousSmallerInteger(n))
# This code is contributed by Anant Agarwal.
C#
1588
Chapter 255. Previous smaller integer having one less number of set bits
PHP
<?php
// PHP implementation to find the previous
// smaller integer with one less number of
// set bits
// function to find the position of
// rightmost set bit.
function getFirstSetBitPos($n)
{
return log($n & -$n) + 1;
}
// function to find the previous
// smaller integer
function previousSmallerInteger($n)
{
// position of rightmost set bit of n
$pos = getFirstSetBitPos($n);
// turn off or unset the bit at
// position 'pos'
return ($n & ~(1 << ($pos - 1)));
}
// Driver Code
$n = 25;
echo "Previous smaller Integer = ", previousSmallerInteger($n);
// This code is contributed by Ajit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/previous-smaller-integer-one-less-number-set-bits/
1589
Chapter 256
Input : l = 6, r = 10
Output : 4
Explanation :
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
9 -> 1001 (2 set bits, 2 is prime)
10 -> 1010 (2 set bits, 2 is prime)
Hence count is 4
Input : l = 10, r = 15
Output : 5
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
Hence count is 5
Explanation: In this program we find a total number, that’s having prime number of set
bit. so we use a CPP predefined function __builtin_popcount() these functions provide
a total set bit in number. as well as be check the total bit’s is prime or not if prime we
increase the counter these process repeat till given range.
1590
Chapter 256. Prime Number of Set Bits in Binary Representation | Set 1
1591
Chapter 256. Prime Number of Set Bits in Binary Representation | Set 1
Output:
Source
https://www.geeksforgeeks.org/prime-number-of-set-bits-in-binary-representation-set-1/
1592
Chapter 257
Input : abc
Output : a, b, c, ab, ac, bc, abc
Input : aab
Output : a, b, aa, ab, aab
Approah 1 :
Here, we discuss much easier and simpler iterative approach which is similar to Power Set.
We use bit pattern from binary representation of 1 to 2^length(s) – 1.
input = “abc”
Binary representation to consider 1 to (2^3-1), i.e 1 to 7.
Start from left (MSB) to right (LSB) of binary representation and append characters from
input string which corresponds to bit value 1 in binary representation to Final subsequence
string sub.
Example:
001 => abc . Only c corresponds to bit 1. So, subsequence = c.
101 => abc . a and c corresponds to bit 1. So, subsequence = ac.
binary_representation (1) = 001 => c
binary_representation (2) = 010 => b
binary_representation (3) = 011 => bc
binary_representation (4) = 100 => a
1593
Chapter 257. Print all subsequences of a string | Iterative Method
1594
Chapter 257. Print all subsequences of a string | Iterative Method
for (auto it : sorted_subsequence) {
// it.first is length of Subsequence
// it.second is set<string>
cout << "Subsequences of length = "
<< it.first << " are:" << endl;
for (auto ii : it.second)
// ii is iterator of type set<string>
cout << ii << " ";
cout << endl;
}
}
// driver function
int main()
{
string s = "aabc";
possibleSubsequences(s);
return 0;
}
Output:
1595
Chapter 257. Print all subsequences of a string | Iterative Method
1596
Chapter 257. Print all subsequences of a string | Iterative Method
}
// function to print all subsequences
void possibleSubsequences(string s){
// map to store subsequence
// lexicographically by length
map<int, set<string> > sorted_subsequence;
int len = s.size();
// Total number of non-empty subsequence
// in string is 2^len-1
int limit = pow(2, len);
// i=0, corresponds to empty subsequence
for (int i = 1; i <= limit - 1; i++) {
// subsequence for binary pattern i
string sub = subsequence(s, i);
// storing sub in map
sorted_subsequence[sub.length()].insert(sub);
}
for (auto it : sorted_subsequence) {
// it.first is length of Subsequence
// it.second is set<string>
cout << "Subsequences of length = "
<< it.first << " are:" << endl;
for (auto ii : it.second)
// ii is iterator of type set<string>
cout << ii << " ";
cout << endl;
}
}
// driver function
int main()
{
string s = "aabc";
possibleSubsequences(s);
return 0;
1597
Chapter 257. Print all subsequences of a string | Iterative Method
Output:
Source
https://www.geeksforgeeks.org/print-subsequences-string-iterative-method/
1598
Chapter 258
Print all the combinations of N elements by changing sign such that their sum is divisible
by M - GeeksforGeeks
Given an array of N integers and an integer M. You can change the sign(positive or negative)
of any element in the array. The task is to print all possible combinations of the array
elements that can be obtained by changing the sign of the elements such that their sum is
divisible by M.
Note: You have to take all of the array elements in each combination and in the same order
as the elements present in the array. However, you can change the sign of elements.
Examples:
Approach: The concept of power set is used here to solve this problem. Using power-set
generate all possible combinations of signs that can be applied to the array of elements. If
the sum obtained is divisible by M, then print the combination. Below are the steps:
1599
Chapter 258. Print all the combinations of N elements by changing sign such that their
sum is divisible by M
• Iterate for all possible combinations of ‘+’ and ‘-‘ using power set.
• Iterate on the array elements and if the j-th bit from left is set, then assume the array
element to be positive and if the bit is not set, then assume the array element to be
negative. Refer here to check if bit any index is set or not.
• If the sum is divisible by M, then the again traverse the array elements and print them
along with sign( ‘+’ or ‘-‘ ).
C++
#include <bits/stdc++.h>
using namespace std;
// Function to print all the combinations
void printCombinations(int a[], int n, int m)
{
// Iterate for all combinations
for (int i = 0; i < (1 << n); i++) {
int sum = 0;
// Initially 100 in binary if n is 3
// as 1<<(3-1) = 100 in binary
int num = 1 << (n - 1);
// Iterate in the array and assign signs
// to the array elements
for (int j = 0; j < n; j++) {
// If the j-th bit from left is set
// take '+' sign
if (i & num)
sum += a[j];
else
sum += (-1 * a[j]);
// Right shift to check if
// jth bit is set or not
num = num >> 1;
}
if (sum % m == 0) {
// re-initialize
num = 1 << (n - 1);
1600
Chapter 258. Print all the combinations of N elements by changing sign such that their
sum is divisible by M
Java
import java.io.*;
class GFG
{
// Function to print
// all the combinations
static void printCombinations(int a[],
int n, int m)
{
// Iterate for all
// combinations
for (int i = 0;
i < (1 << n); i++)
{
int sum = 0;
1601
Chapter 258. Print all the combinations of N elements by changing sign such that their
sum is divisible by M
1602
Chapter 258. Print all the combinations of N elements by changing sign such that their
sum is divisible by M
System.out.println();
}
}
}
// Driver code
public static void main(String args[])
{
int a[] = { 3, 5, 6, 8 };
int n = a.length;
int m = 5;
printCombinations(a, n, m);
}
}
// This code is contributed
// by inder_verma.
Python3
# Function to print
# all the combinations
def printCombinations(a, n, m):
# Iterate for all
# combinations
for i in range(0, (1 << n)):
sum = 0
# Initially 100 in binary
# if n is 3 as
# 1<<(3-1) = 100 in binary
num = 1 << (n - 1)
# Iterate in the array
# and assign signs to
# the array elements
for j in range(0, n):
# If the j-th bit
# from left is set
# take '+' sign
if ((i & num) > 0):
sum += a[j]
else:
sum += (-1 * a[j])
1603
Chapter 258. Print all the combinations of N elements by changing sign such that their
sum is divisible by M
# Right shift to check if
# jth bit is set or not
num = num >> 1
if (sum % m == 0):
# re-initialize
num = 1 << (n - 1)
# Iterate in the
# array elements
for j in range(0, n):
# If the jth from
# left is set
if ((i & num) > 0):
print("+", a[j], end = " ",
sep = "")
else:
print("-", a[j], end = " ",
sep = "")
# right shift
num = num >> 1
print("")
# Driver code
a = [ 3, 5, 6, 8 ]
n = len(a)
m = 5
printCombinations(a, n, m)
# This code is contributed
# by smita.
C#
1604
Chapter 258. Print all the combinations of N elements by changing sign such that their
sum is divisible by M
1605
Chapter 258. Print all the combinations of N elements by changing sign such that their
sum is divisible by M
Output:
-3 -5 +6 -8
-3 +5 +6 -8
+3 -5 -6 +8
+3 +5 -6 +8
Source
https://www.geeksforgeeks.org/print-all-the-combinations-of-n-elements-by-changing-sign-such-that-their-sum-is-d
1606
Chapter 259
Examples :
Input : N = 5
Output : 0, 1, 4, 5
Explanation: 0 & 5 = 0
1 & 5 = 1
2 & 5 = 0
3 & 5 = 1
4 & 5 = 4
5 & 5 = 5
So we get 0, 1, 4 and 5 in the
bitwise subsets of N.
Input : N = 9
Output : 0, 1, 8, 9
Simple Approach: A naive approach is to iterate from all numbers from 0 to N and check
if (N&i == i). Print the numbers which satisfy the specified condition.
Below is the implementation of above idea:
C++
1607
Chapter 259. Print bitwise AND set of a number N
Java
1608
Chapter 259. Print bitwise AND set of a number N
Python3
C#
PHP
1609
Chapter 259. Print bitwise AND set of a number N
<?php
// PHP program to print all bitwise
// subsets of N (Naive approach)
// function to find bitwise subsets
// Naive approach
function printSubsets($n)
{
for ($i = 0; $i <= $n; $i++)
if (($n & $i) == $i)
echo $i." ";
}
// Driver Code
$n = 9;
printSubsets($n);
// This code is contributed by mits
?>
Output :
0 1 8 9
CPP
1610
Chapter 259. Print bitwise AND set of a number N
// Driver Code
int main() {
int n = 9;
printSubsets(n);
return 0;
}
Java
Python3
# Python 3 program to
# print all bitwise
# subsets of N
# (Efficient approach)
# fucntion to find
# bitwise subsets
# Efficient approach
1611
Chapter 259. Print bitwise AND set of a number N
def printSubsets(n):
i=n
while(i != 0):
print(i,end=" ")
i=(i - 1) & n
print("0")
# Driver Code
n = 9
printSubsets(n)
# This code is contributed by
# Smith Dinesh Semwal
C#
PHP
<?php
// PHP program to print all bitwise
// subsets of N (Efficient approach)
1612
Chapter 259. Print bitwise AND set of a number N
// function to find bitwise subsets
// Efficient approach
function printSubsets($n)
{
for ($i = $n; $i > 0;
$i = ($i - 1) & $n)
echo $i." ";
echo "0";
}
// Driver Code
$n = 9;
printSubsets($n);
// This code is contributed by mits
?>
Output :
9 8 1 0
Source
https://www.geeksforgeeks.org/print-bitwise-and-set-of-a-number-n/
1613
Chapter 260
Input: n = 3
Output: 3 5 6
The first 3 numbers with two set bits are 3 (0011),
5 (0101) and 6 (0110)
Input: n = 5
Output: 3 5 6 9 10 12
A Simple Solution is to consider all positive integers one by one starting from 1. For every
number, check if it has exactly two sets bits. If a number has exactly two set bits, print it
and increment count of such numbers.
An Efficient Solution is to directly generate such numbers. If we clearly observe the
numbers, we can rewrite them as given below pow(2,1)+pow(2,0), pow(2,2)+pow(2,0),
pow(2,2)+pow(2,1), pow(2,3)+pow(2,0), pow(2,3)+pow(2,1), pow(2,3)+pow(2,2), ………
All numbers can be generated in increasing order according to higher of two set bits. The
idea is to fix higher of two bits one by one. For current higher set bit, consider all lower bits
and print the formed numbers.
C++
1614
Chapter 260. Print first n numbers with exactly two set bits
Java
1615
Chapter 260. Print first n numbers with exactly two set bits
1616
Chapter 260. Print first n numbers with exactly two set bits
C#
1617
Chapter 260. Print first n numbers with exactly two set bits
PHP
<?php
// PHP program to print
// first n numbers with
// exactly two set bits
// Prints first n numbers
// with two set bits
function printTwoSetBitNums($n)
{
// Initialize higher of
// two sets bits
$x = 1;
// Keep reducing n for
// every number with
// two set bits.
while ($n > 0)
{
// Consider all lower set
// bits for current higher
// set bit
$y = 0;
while ($y < $x)
{
// Print current number
echo (1 << $x) + (1 << $y), " ";
// If we have found n numbers
$n--;
if ($n == 0)
return;
// Consider next lower
// bit for current
// higher bit.
$y++;
1618
Chapter 260. Print first n numbers with exactly two set bits
}
// Increment higher set bit
$x++;
}
}
// Driver code
printTwoSetBitNums(4);
// This code is contributed by Ajit
?>
Output :
3 5 6 9
Source
https://www.geeksforgeeks.org/print-first-n-numbers-with-exactly-two-set-bits/
1619
Chapter 261
Print numbers having first and last bits as the only set bits - GeeksforGeeks
Given a positive integer n. The problem is to print numbers in the range 1 to n having first
and last bits as the only set bits.
Examples:
Input : n = 10
Output : 1 3 5 9
(1)10 = (1)2.
(3)10 = (11)2.
(5)10 = (101)2.
(9)10 = (1001)2
Naive Approach: Print “1”. Now for i = 3 to n, check if (i-1) is a Perfect power of two
or not. If true then print i.
C++
1620
Chapter 261. Print numbers having first and last bits as the only set bits
bool powerOfTwo(ull n)
{
return (!(n & n-1));
}
// fuction to print numbers in the range 1 to n having
// first and last bits as the only set bits
void printNumWithFirstLastBitsSet(ull n)
{
ull i = 1;
// first number is '1'
cout << i << " ";
// generating all the numbers
for (i = 3; i <= n; i++)
// if true, then print 'i'
if (powerOfTwo(i-1))
cout << i << " ";
}
// Driver program to test above
int main()
{
ull n = 10;
printNumWithFirstLastBitsSet(n);
return 0;
}
Java
// Naive approach
// Java implementation to print
// numbers in the range 1 to n
// having first and last bits as
// the only set bits
import java.io.*;
class GFG {
// function to check whether 'n'
// is a power of 2 or not
static Boolean powerOfTwo(long n)
{
return (!((n & n-1) != 0));
}
// fuction to print numbers in the
1621
Chapter 261. Print numbers having first and last bits as the only set bits
Python3
1622
Chapter 261. Print numbers having first and last bits as the only set bits
C#
// Naive approach
// C# implementation to print
// numbers in the range 1 to n
// having first and last bits as
// the only set bits
using System;
class GFG {
// function to check whether 'n'
// is a power of 2 or not
static Boolean powerOfTwo(long n)
{
return (!((n & n-1) != 0));
}
// fuction to print numbers in the
// range 1 to n having first and
// last bits as the only set bits
static void printNumWithFirstLastBitsSet(long n)
{
long i = 1;
// first number is '1'
Console.Write( i + " ");
// generating all the numbers
for (i = 3; i <= n; i++)
// if true, then print 'i'
1623
Chapter 261. Print numbers having first and last bits as the only set bits
PHP
<?php
// php implementation to print
// numbers in the range 1 to n
// having first and last bits
// as the only set bits
// function to check whether 'n'
// is a power of 2 or not
function powerOfTwo($n)
{
return (!($n & $n - 1));
}
// fuction to print numbers in
// the range 1 to n having
// first and last bits as
// the only set bits
function printNumWithFirstLastBitsSet($n)
{
$i = 1;
// first number is '1'
echo $i." ";
// generating all the numbers
for ($i = 3; $i <= $n; $i++)
// if true, then print 'i'
if (powerOfTwo($i - 1))
echo $i." ";
}
1624
Chapter 261. Print numbers having first and last bits as the only set bits
// Driver Code
$n = 10;
printNumWithFirstLastBitsSet($n);
// This Code is contributed by mits
?>
Output:
1 3 5 9
1625
Chapter 261. Print numbers having first and last bits as the only set bits
Java
1626
Chapter 261. Print numbers having first and last bits as the only set bits
// display
System.out.print(num + " ");
}
}
public static void main (String[] args) {
long n = 10;
prNumWithFirstLastBitsSet(n);
}
}
// This code is contributed by Gitanjali.
Python3
1627
Chapter 261. Print numbers having first and last bits as the only set bits
# Driver program
n = 10;
prNumWithFirstLastBitsSet(n)
# This code is contributed by saloni1297
C#
1628
Chapter 261. Print numbers having first and last bits as the only set bits
PHP
<?php
// php implementation to print
// numbers in the range 1 to n
// having first and last bits
// as the only set bits
// fuction to print numbers in
// the range 1 to n having
// first and last bits as
// the only set bits
function printNumWithFirstLastBitsSet($n)
{
$power_2 = 1;
// first number is '1'
echo $power_2." ";
while (1)
{
// obtaining next perfect
// power of 2
$power_2 <<= 1;
// toggling the last
// bit to convert
// it to as set bit
$num = $power_2 ^ 1;
// if out of range
// then break;
if ($n < $num)
break;
// display
echo $num." ";
}
1629
Chapter 261. Print numbers having first and last bits as the only set bits
}
// Driver code
$n = 10;
printNumWithFirstLastBitsSet($n);
// This code is contributed by mits
?>
Output:
1 3 5 9
Source
https://www.geeksforgeeks.org/print-numbers-first-last-bits-set-bits/
1630
Chapter 262
Input : n = 10
Output : 1 2 5 10
Input : n = 50
Output : 1 2 5 10 21 42
Method 1 (Naive Approach): Generate all the numbers in the range 1 to n and for each
generated number check whether it has bits in alternate pattern. Time Complexity is of
O(n).
Method 2 (Efficient Approach): Algorithm:
printNumHavingAltBitPatrn(n)
Initialize curr_num = 1
print curr_num
while (1)
curr_num <<= 1
if n < curr_num then
1631
Chapter 262. Print numbers in the range 1 to n having bits in alternate pattern
break
print curr_num
curr_num = ((curr_num) << 1) ^ 1
if n < curr_num then
break
print curr_num
CPP
1632
Chapter 262. Print numbers in the range 1 to n having bits in alternate pattern
Java
1633
Chapter 262. Print numbers in the range 1 to n having bits in alternate pattern
// if true then break
if (n < curr_num)
break;
// display
System.out.print(curr_num + " ");
}
}
public static void main (String[] args)
{
int n = 50;
printNumHavingAltBitPatrn(n);
}
}
// Code Contributed by Mohit Gupta_OMG <(0_o)>
Python3
1634
Chapter 262. Print numbers in the range 1 to n having bits in alternate pattern
C#
1635
Chapter 262. Print numbers in the range 1 to n having bits in alternate pattern
// display
Console.Write(curr_num + " ");
// generate next number having alternate
// bit pattern
curr_num = ((curr_num) << 1) ^ 1;
// if true then break
if (n < curr_num)
break;
// display
Console.Write(curr_num + " ");
}
}
// Driver code
public static void Main ()
{
int n = 50;
printNumHavingAltBitPatrn(n);
}
}
// This code is contributed by Sam007.
PHP
<?php
// php implementation to print
// numbers in the range
// 1 to n having bits in
// alternate pattern
// function to print numbers
// in the range 1 to n
// having bits in alternate
// pattern
function printNumHavingAltBitPatrn($n)
{
// first number having bits
// in alternate pattern
$curr_num = 1;
// display
1636
Chapter 262. Print numbers in the range 1 to n having bits in alternate pattern
Output:
1 2 5 10 21 42
1637
Chapter 262. Print numbers in the range 1 to n having bits in alternate pattern
Source
https://www.geeksforgeeks.org/print-numbers-range-1-n-bits-alternate-pattern/
1638
Chapter 263
Approach:
Finding Maximum AND value is same as Maximum AND value in an array. Our task is
to find the pair of elements resulting in obtained AND value. For finding the elements,
simply traverse the whole array and find the AND value of each element with the obtained
maximum AND value (result) and if arr[i] & result == result , that means arr[i] is the
element which will generate maximum AND value. Also, in the case if maximum AND value
(result) is zero then we should print “Not possible” in that case.
Below is the implementation of above approach:
C++
1639
Chapter 263. Print pair with maximum AND value in an array
1640
Chapter 263. Print pair with maximum AND value in an array
Java
1641
Chapter 263. Print pair with maximum AND value in an array
{
int res = 0, count;
// iterate over total of 30bits
// from msb to lsb
for (int bit = 31; bit >= 0; bit--) {
// find the count of element
// having set msb
count = checkBit(res | (1 << bit), arr, n);
// if count >= 2 set particular
// bit in result
if (count >= 2)
res |= (1 << bit);
}
// Find the elements
if (res == 0)
System.out.println("Not Possible");
else {
// print the pair of elements
System.out.print("Pair = ");
count = 0;
for (int i = 0; i < n && count < 2; i++) {
// inc count value after
// printing element
if ((arr[i] & res) == res) {
count++;
System.out.print(arr[i] + " ");
}
}
System.out.println();
}
// return the result value
return res;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 4, 8, 6, 2 };
1642
Chapter 263. Print pair with maximum AND value in an array
int n = arr.length;
System.out.println("Maximum AND Value = "
+ maxAND(arr, n));
}
}
// This code is contributed by Sahil_Bansall
Python 3
1643
Chapter 263. Print pair with maximum AND value in an array
else:
# print the pair of elements
print("Pair = ", end = "")
count = 0
i = 0
while(i < n and count < 2):
# inc count value after
# printing element
if ((arr[i] & res) == res) :
count+=1
print(arr[i] , end = " ")
i += 1
# return the result value
return res
# Driver function
arr = [4, 8, 6, 2 ]
n = len(arr)
print("\nMaximum AND Value = ",
maxAND(arr, n))
# This code is contributed by Smitha
C#
1644
Chapter 263. Print pair with maximum AND value in an array
1645
Chapter 263. Print pair with maximum AND value in an array
PHP
<?php
// php Program to find pair with
// maximum AND value
// Utility function to check number of
// elements having set msb as of pattern
function checkBit($pattern, $arr, $n)
{
$count = 0;
for ($i = 0; $i < $n; $i++)
if (($pattern & $arr[$i]) == $pattern)
$count++;
return $count;
}
// Function for finding maximum
// and value pair
function maxAND($arr, $n)
{
$res = 0;
// iterate over total of 30bits
// from msb to lsb
for ($bit = 31; $bit >= 0; $bit--)
{
// find the count of element
// having set msb
$count = checkBit($res | (1 << $bit),
$arr, $n);
// if count >= 2 set particular
// bit in result
1646
Chapter 263. Print pair with maximum AND value in an array
Output:
Pair = 4 6
Maximum AND value = 4
1647
Chapter 263. Print pair with maximum AND value in an array
Source
https://www.geeksforgeeks.org/print-pair-with-maximum-and-value-in-an-array/
1648
Chapter 264
C++
1649
Chapter 264. Print ‘K’th least significant bit of a number
java
1650
Chapter 264. Print ‘K’th least significant bit of a number
Python
C#
1651
Chapter 264. Print ‘K’th least significant bit of a number
PHP
<?php
// PHP code to print 'K'th LSB
// Function returns 1 if set, 0 if not
function LSB($num, $K)
{
return ($num & (1 << ($K - 1)));
}
// Driver code
$num = 10;
$K = 4;
$r = LSB($num, $K);
if($r)
echo '1';
else
echo '0';
// This code is contributed by Ajit
?>
Output :
Source
https://www.geeksforgeeks.org/print-kth-least-significant-bit-number/
1652
Chapter 265
0, 1, 2, 3
0 - 0, 1, 1, 2 -------- GROUP_A(0)
4 - 1, 2, 2, 3 -------- GROUP_A(1)
8 - 1, 2, 2, 3 -------- GROUP_A(1)
12 - 2, 3, 3, 4 -------- GROUP_A(2)
1653
Chapter 265. Program to count number of set bits in an (big) array
16 - 1, 2, 2, 3 -------- GROUP_A(1)
20 - 2, 3, 3, 4 -------- GROUP_A(2)
24 - 2, 3, 3, 4 -------- GROUP_A(2)
28 - 3, 4, 4, 5 -------- GROUP_A(3) ... so on
From the table, there is a patten emerging in multiples of 4, both in the table as well as in
the group parameter. The sequence can be generalized as shown in the code.
Complexity:
All the operations takes O(1) except iterating over the array. The time complexity is O(n)
where ‘n’ is size of array. Space complexity depends on the meta program that generates
look up.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Size of array 64 K */
#define SIZE (1 << 16)
/* Meta program that generates set bit count
array of first 256 integers */
/* GROUP_A - When combined with META_LOOK_UP
generates count for 4x4 elements */
#define GROUP_A(x) x, x + 1, x + 1, x + 2
/* GROUP_B - When combined with META_LOOK_UP
generates count for 4x4x4 elements */
#define GROUP_B(x) GROUP_A(x), GROUP_A(x+1), GROUP_A(x+1), GROUP_A(x+2)
/* GROUP_C - When combined with META_LOOK_UP
generates count for 4x4x4x4 elements */
#define GROUP_C(x) GROUP_B(x), GROUP_B(x+1), GROUP_B(x+1), GROUP_B(x+2)
/* Provide appropriate letter to generate the table */
#define META_LOOK_UP(PARAMETER) \
GROUP_##PARAMETER(0), \
GROUP_##PARAMETER(1), \
GROUP_##PARAMETER(1), \
GROUP_##PARAMETER(2) \
1654
Chapter 265. Program to count number of set bits in an (big) array
1655
Chapter 265. Program to count number of set bits in an (big) array
Contributed by Venki. Please write comments if you find anything incorrect, or you want
to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/program-to-count-number-of-set-bits-in-an-big-array/
1656
Chapter 266
Algorithm: getParity(n)
1. Initialize parity = 0
2. Loop while n != 0
a. Invert parity
parity = !parity
b. Unset rightmost set bit
n = n & (n-1)
3. return parity
Example:
Initialize: n = 13 (1101) parity = 0
Program:
# include <stdio.h>
# define bool int
1657
Chapter 266. Program to find parity
/* Function to get parity of number n. It returns 1
if n has odd parity, and returns 0 if n has even
parity */
bool getParity(unsigned int n)
{
bool parity = 0;
while (n)
{
parity = !parity;
n = n & (n - 1);
}
return parity;
}
/* Driver program to test getParity() */
int main()
{
unsigned int n = 7;
printf("Parity of no %d = %s", n,
(getParity(n)? "odd": "even"));
getchar();
return 0;
}
Java
1658
Chapter 266. Program to find parity
return parity;
}
/* Driver program to test getParity() */
public static void main (String[] args)
{
int n = 12;
System.out.println("Parity of no " + n + " = " +
(getParity(n)? "odd": "even"));
}
}
/* This code is contributed by Amit khandelwal*/
Python3
C#
1659
Chapter 266. Program to find parity
PHP
<?php
// PHP program to find the parity
// of an unsigned integer
// Function to get parity of
// number n. It returns 1
// if n has odd parity, and
// returns 0 if n has even
// parity
function getParity( $n)
{
$parity = 0;
while ($n)
{
$parity = !$parity;
$n = $n & ($n - 1);
}
return $parity;
}
// Driver Code
$n = 7;
echo "Parity of no ",$n ," = " ,
getParity($n)? "odd": "even";
1660
Chapter 266. Program to find parity
// This code is contributed by anuj_67.
?>
Output:
Parity of no 7 = odd
Above solution can be optimized by using lookup table. Please refer to Bit Twiddle Hacks[1st
reference] for details.
Time Complexity: The time taken by above algorithm is proportional to the number of
bits set. Worst case complexity is O(Log n).
Uses: Parity is used in error detection and cryptography.
Source
https://www.geeksforgeeks.org/program-to-find-parity/
1661
Chapter 267
Input : n = 4
Output : Yes
22 = 4
Input : n = 7
Output : No
Input : n = 32
Output : Yes
25 = 32
1. A simple method for this is to simply take the log of the number on base 2 and if you
get an integer then number is power of 2.
C
#include<stdio.h>
#include<stdbool.h>
#include<math.h>
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
1662
Chapter 267. Program to find whether a no is power of two
PHP
<?php
// PHP Program to find
// whether a no is
// power of two
// Function to check
// Log base 2
function Log2($x)
{
return (log10($x) /
log10(2));
}
// Function to check
// if x is power of 2
function isPowerOfTwo($n)
{
return (ceil(Log2($n)) ==
floor(Log2($n)));
}
// Driver Code
if(isPowerOfTwo(31))
echo "Yes\n";
else
echo "No\n";
if(isPowerOfTwo(64))
echo "Yes\n";
else
echo "No\n";
1663
Chapter 267. Program to find whether a no is power of two
Python3
# Python3 Program to find
# whether a no is
# power of two
import math
# Function to check
# Log base 2
def Log2(x):
return (math.log10(x) /
math.log10(2));
# Function to check
# if x is power of 2
def isPowerOfTwo(n):
return (math.ceil(Log2(n)) ==
math.floor(Log2(n)));
# Driver Code
if(isPowerOfTwo(31)):
print(“Yes”);
else:
print(“No”);
if(isPowerOfTwo(64)):
print(“Yes”);
else:
print(“No”);
# This code is contributed
# by mits
Output:
No
Yes
2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively.
In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n
becomes 1 then it is a power of 2.
#include<stdio.h>
#include<stdbool.h>
1664
Chapter 267. Program to find whether a no is power of two
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
if (n == 0)
return 0;
while (n != 1)
{
if (n%2 != 0)
return 0;
n = n/2;
}
return 1;
}
/*Driver program to test above function*/
int main()
{
isPowerOfTwo(31)? printf("Yes\n"): printf("No\n");
isPowerOfTwo(64)? printf("Yes\n"): printf("No\n");
return 0;
}
Java
1665
Chapter 267. Program to find whether a no is power of two
Python3
C#
1666
Chapter 267. Program to find whether a no is power of two
// a no is power of two
using System;
class GFG
{
// Function to check if
// x is power of 2
static bool isPowerOfTwo(int n)
{
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
// Driver program
public static void Main()
{
Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
}
}
// This code is contributed by Sam007
PHP
<?php
// Function to check if
// x is power of 2
function isPowerOfTwo($n)
{
if ($n == 0)
return 0;
while ($n != 1)
{
if ($n % 2 != 0)
return 0;
$n = $n / 2;
1667
Chapter 267. Program to find whether a no is power of two
}
return 1;
}
// Driver Code
if(isPowerOfTwo(31))
echo "Yes\n";
else
echo "No\n";
if(isPowerOfTwo(64))
echo "Yes\n";
else
echo "No\n";
// This code is contributed
// by Sam007
?>
Output :
No
Yes
3. All power of two numbers have only one bit set. So count the no. of set bits and if you
get 1 then number is a power of 2. Please see Count set bits in an integer for counting set
bits.
4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become
set; and the set bit become unset.
For example for 4 ( 100) and 16(10000), we get following after subtracting 1
3 –> 011
15 –> 01111
So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is
a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when
n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https:
//www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for
adding this case).
Below is the implementation of this method.
#include<stdio.h>
#define bool int
/* Function to check if x is power of 2*/
1668
Chapter 267. Program to find whether a no is power of two
Java
Python
1669
Chapter 267. Program to find whether a no is power of two
# First x in the below expression
# is for the case when x is 0
return (x and (not(x & (x - 1))) )
# Driver code
if(isPowerOfTwo(31)):
print('Yes')
else:
print('No')
if(isPowerOfTwo(64)):
print('Yes')
else:
print('No')
# This code is contributed by Danish Raza
C#
// C# program to efficiently
// check for power for 2
using System;
class GFG
{
// Method to check if x is power of 2
static bool isPowerOfTwo (int x)
{
// First x in the below expression
// is for the case when x is 0
return x != 0 && ((x & (x - 1)) == 0);
}
// Driver method
public static void Main()
{
Console.WriteLine(isPowerOfTwo(31) ? "Yes" : "No");
Console.WriteLine(isPowerOfTwo(64) ? "Yes" : "No");
}
}
// This code is contributed by Sam007
PHP
1670
Chapter 267. Program to find whether a no is power of two
<?php
// PHP program to efficiently
// check for power for 2
// Function to check if
// x is power of 2
function isPowerOfTwo ($x)
{
// First x in the below expression
// is for the case when x is 0
return $x && (!($x & ($x - 1)));
}
// Driver Code
if(isPowerOfTwo(31))
echo "Yes\n" ;
else
echo "No\n";
if(isPowerOfTwo(64))
echo "Yes\n" ;
else
echo "No\n";
// This code is contributed by Sam007
?>
Output :
No
Yes
Source
https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/
1671
Chapter 268
Input : 11
Output : 4
(11)10 = (1011)2
After inverting the bits, we get:
(0100)2 = (4)10.
Input : 20
Output : 11
(20)10 = (10100)2.
After inverting the bits, we get:
(01011)2 = (11)10.
1. Calculate the total number of bits in the given number. This can be done by calculat-
ing:
1672
Chapter 268. Program to invert bits of a number Efficiently
X = log2N
Step-1: M = 1 << X
Step-2: M = M | (M-1)
1673
Chapter 268. Program to invert bits of a number Efficiently
Output:
11
Source
https://www.geeksforgeeks.org/program-to-invert-bits-of-a-number-efficiently/
1674
Chapter 269
Input : number = 72
k = 5
p = 1
Output : The extracted number is 8
72 is represented as 1001000 in binary,
so, you should get only 01000 i.e 8.
We have existing solution for this problem please refer Extract ‘k’ bits from a given position
in a number link. We can solve this problem quickly in python using slicing. Approach is
simple,
1. Convert given number into it’s binary using bin() function and remove first two char-
acters ‘0b’ from it, because bin function appends ‘0b’ as prefix in output binary string.
2. We need to start extracting k bits from starting position p from right, that means end
index of extracted sub-string will be end = (len(binary) – p) and start index will
be start = end – k + 1 of original binary string.
1675
Chapter 269. Python Slicing | Extract ‘k’ bits from a given position
Output:
21
Source
https://www.geeksforgeeks.org/python-slicing-extract-k-bits-given-position/
1676
Chapter 270
Python map function | Count total set bits in all numbers from 1 to n - GeeksforGeeks
Given a positive integer n, count the total number of set bits in binary representation of all
numbers from 1 to n.
Examples:
Input: n = 3
Output: 4
Binary representations are 1, 2 and 3
1, 10 and 11 respectively. Total set
bits are 1 + 1 + 2 = 4.
Input: n = 6
Output: 9
Input: n = 7
Output: 12
Input: n = 8
Output: 13
We have existing solution for this problem please refer Count total set bits in all numbers
from 1 to n link. We can solve this problem in python using map() function. Approach is
very simple,
1677
Chapter 270. Python map function | Count total set bits in all numbers from 1 to n
1. Write a function which first converts number into binary using bin(num) function and
returns count of set bits in it.
2. Map user defined function on list of numbers from 1 to n and we will get list of
individual count of set bits in each number.
3. Sum up count of all set bits.
Output:
13
Source
https://www.geeksforgeeks.org/python-map-function-count-total-set-bits-numbers-1-n/
1678
Chapter 271
1679
Chapter 271. Python program to convert floating to binary
# split() seperates whole number and decimal
# part and stores it in two seperate variables
whole, dec = str(number).split(".")
# Convert both whole number and decimal
# part from string type to integer type
whole = int(whole)
dec = int (dec)
# Convert the whole number part to it's
# respective binary form and remove the
# "0b" from it.
res = bin(whole).lstrip("0b") + "."
# Iterate the number of times, we want
# the number of decimal places to be
for x in range(places):
# Multiply the decimal value by 2
# and seperate the whole number part
# and decimal part
whole, dec = str((decimal_converter(dec)) * 2).split(".")
# Convert the decimal part
# to integer again
dec = int(dec)
# Keep adding the integer parts
# receive to the result variable
res += whole
return res
# Function converts the value passed as
# parameter to it's decimal representation
def decimal_converter(num):
while num > 1:
num /= 10
return num
# Driver Code
# Take the user input for
# the floating point number
n = input("Enter your floating point value : \n")
# Take user input for the number of
1680
Chapter 271. Python program to convert floating to binary
Output :
1.0011
1011.0011
Source
https://www.geeksforgeeks.org/python-program-to-convert-floating-to-binary/
1681
Chapter 272
Input : n = 42, l = 2, r = 5
Output : 2
(42)10 = (101010)2
There are '2' set bits in the range 2 to 5.
Input : n = 79, l = 1, r = 4
Output : 4
We have existing solution for this problem please refer Count set bits in a range link. We
can solve this problem quickly in Python. Approach is very simple,
1682
Chapter 272. Python | Count set bits in a range
def countSetBits(n,l,r):
# convert n into it's binary
binary = bin(n)
# remove first two characters
binary = binary[2:]
# reverse string
binary = binary[-1::-1]
# count all set bit '1' starting from index l-1
# to r, where r is exclusive
print (len([binary[i] for i in range(l-1,r) if binary[i]=='1']))
# Driver program
if __name__ == "__main__":
n=42
l=2
r=5
countSetBits(n,l,r)
Output:
Source
https://www.geeksforgeeks.org/python-count-set-bits-range/
1683
Chapter 273
Input : n = 42, l = 2, r = 5
Output : 2
(42)10 = (101010)2
There are '2' unset bits in the range 2 to 5.
Input : n = 80, l = 1, r = 4
Output : 4
We have existing solution for this problem please refer Count unset bits in a range link. We
can solve this problem quickly in Python. Approach is very simple,
1684
Chapter 273. Python | Count unset bits in a range
# convert n into it's binary
binary = bin(n)
# remove first two characters
binary = binary[2:]
# reverse string
binary = binary[-1::-1]
# count all unset bit '0' starting from index l-1
# to r, where r is exclusive
print (len([binary[i] for i in range(l-1,r) if binary[i]=='0']))
# Driver program
if __name__ == "__main__":
n=42
l=2
r=5
unsetBits(n,l,r)
Output:
Source
https://www.geeksforgeeks.org/python-count-unset-bits-range/
1685
Chapter 274
Queries for number of array elements in a range with Kth Bit Set - GeeksforGeeks
Given an array of N positive (32-bit)integers, the task is to answer Q queries of the following
form:
Input : arr[] = { 8, 9, 1, 3 }
Query 1: L = 1, R = 3, K = 4
Query 2: L = 2, R = 4, K = 1
Output :
2
3
Explanation:
For the 1st query, the range (1, 3) represents elements, {8, 9, 1}. Among these
elements only 8 and 9 have their 4th bit set. Thus, the answer for this query is
2.
For the 2nd query, the range (2, 4) represents elements, {9, 1, 3}. All of these
elements have their 1st bit set. Thus, the answer for this query is 3.
1686
Chapter 274. Queries for number of array elements in a range with Kth Bit Set
C++
1687
Chapter 274. Queries for number of array elements in a range with Kth Bit Set
{
int query_L, query_R, query_K;
for (int i = 0; i < Q; i++) {
query_L = queries[i][0] - 1;
query_R = queries[i][1] - 1;
query_K = queries[i][2];
cout << "Result for Query " << i + 1 << " = "
<< answerQuery(query_L, query_R, query_K, arr)
<< endl;
}
}
// Driver Code
int main()
{
int arr[] = { 8, 9, 1, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
/* queries[][] denotes the array of queries
where each query has three integers
query[i][0] -> Value of L for ith query
query[i][0] -> Value of R for ith query
query[i][0] -> Value of K for ith query */
int queries[][3] = {
{ 1, 3, 4 },
{ 2, 4, 1 }
};
int Q = sizeof(queries) / sizeof(queries[0]);
answerQueries(queries, Q, arr, N);
return 0;
}
Java
1688
Chapter 274. Queries for number of array elements in a range with Kth Bit Set
// in binary represention
// of an array element
class GFG
{
static final int MAX_BITS = 32;
/* Returns true if n
has its kth bit as set,
else returns false */
static boolean isKthBitSet(int n,
int k)
{
if ((n & (1 << (k - 1))) != 0)
return true;
return false;
}
/* Returns the answer for
each query with range L
to R querying for the number
of elements with the Kth bit
set in the range */
static int answerQuery(int L, int R,
int K, int arr[])
{
// counter stores the number
// of element in the range
// with the kth bit set
int counter = 0;
for (int i = L; i <= R; i++)
{
if (isKthBitSet(arr[i], K))
{
counter++;
}
}
return counter;
}
// Print the answer
// for all queries
static void answerQueries(int queries[][], int Q,
int arr[], int N)
{
int query_L, query_R, query_K;
for (int i = 0; i < Q; i++)
{
1689
Chapter 274. Queries for number of array elements in a range with Kth Bit Set
query_L = queries[i][0] - 1;
query_R = queries[i][1] - 1;
query_K = queries[i][2];
System.out.println("Result for Query " +
(i + 1) + " = " +
answerQuery(query_L, query_R,
query_K, arr));
}
}
// Driver Code
public static void main(String args[])
{
int arr[] = { 8, 9, 1, 3 };
int N = arr.length;
/* queries[][] denotes the array
of queries where each query has
three integers
query[i][0] -> Value of L for ith query
query[i][0] -> Value of R for ith query
query[i][0] -> Value of K for ith query */
int queries[][] =
{
{ 1, 3, 4 },
{ 2, 4, 1 }
};
int Q = queries.length;
answerQueries(queries, Q, arr, N);
}
}
// This code is contributed
// by Subhadeep
Output:
1690
Chapter 274. Queries for number of array elements in a range with Kth Bit Set
the 2nd dimension of the prefix array is of size equal to the maximum number of bits
required to represent a integer of the array in binary.
Let the Prefix Sum Array be P[][]. Now, P[i][j] denotes the number of Elements from 0 to
i, which have their jth bit as set. This prefix sum array is built before answering the queries.
If a query from L to R is encountered, querying for elements in this range having their Kth
bit as set, then the answer for that query is P[R][K] – P[L – 1][K].
Below is the implementation of above approach.
C++
1691
Chapter 274. Queries for number of array elements in a range with Kth Bit Set
1692
Chapter 274. Queries for number of array elements in a range with Kth Bit Set
cout << "Result for Query " << i + 1 << " = "
<< answerQuery(query_L, query_R, query_K, P)
<< endl;
}
}
// Driver Code
int main()
{
int arr[] = { 8, 9, 1, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
/* queries[][] denotes the array of queries
where each query has three integers
query[i][0] -> Value of L for ith query
query[i][0] -> Value of R for ith query
query[i][0] -> Value of K for ith query */
int queries[][3] = {
{ 1, 3, 4 },
{ 2, 4, 1 }
};
int Q = sizeof(queries) / sizeof(queries[0]);
answerQueries(queries, Q, arr, N);
return 0;
}
Output:
Time Complexity of building the Prefix array is O(N * Maximum number of Bits) and
each query is answered in O(1).
Auxiliary space : O(N * Maximum Number of Bits) is required to build the Prefix Sum
Array
Improved By : tufan_gupta2000
Source
https://www.geeksforgeeks.org/queries-for-number-of-array-elements-in-a-range-with-kth-bit-set/
1693
Chapter 275
Input : A[] = { 1, 2, 3, 4, 5 }, Q = 3
q1 = { 1, 2 }
q2 = { 1, 3 }
q3 = { 2, 4 }
Output : 0
2
6
For query 1, the extracted array is [1, 2] and
subarrays of the array is [1], [2], [1, 2].
So, the answer is (1) � (2) � (1 � 2) = 0.
For query 2, the extracted array is [1, 2, 3] and
subarrays of the array is
[1], [2], [1, 2], [2, 3], [1, 2, 3].
So the answer is (1) � (2) � (3) � (1 � 2) �
(2 � 3) � (1 � 2 � 3) = 2.
For query 3, the extracted array is [2, 3, 4] and
subarrays of the array is
[2], [3], [4], [2, 3], [3, 4], [2, 3, 4].
So the answer is (2) � (3) � (4) � (2 � 3) �
(3 � 4) � (2 � 3 � 4) = 6.
1694
Chapter 275. Queries on XOR of XORs of all subarrays
Input : A[] = { 5, 8, 9, 1, 7 }, Q = 3
query1 = { 1, 3 }
query2 = { 3, 4 }
query3 = { 2, 5 }
Output : 12
0
0
1695
Chapter 275. Queries on XOR of XORs of all subarrays
1696
Chapter 275. Queries on XOR of XORs of all subarrays
int r[] = { 2, 3, 4 };
int q = sizeof(l) / sizeof(l[0]);
ansQueries(arr, n, l, r, q);
return 0;
}
Java
1697
Chapter 275. Queries on XOR of XORs of all subarrays
C#
1698
Chapter 275. Queries on XOR of XORs of all subarrays
using System;
class GFG {
// Output for each query
static void ansQueries(int[] prefeven,
int[] prefodd,
int l, int r)
{
// If number of element is even.
if ((r - l + 1) % 2 == 0)
Console.WriteLine("0");
// If number of element is odd.
else {
// if l is even
if (l % 2 == 0)
Console.WriteLine(prefeven[r] ^ prefeven[l - 1]);
// if l is odd
else
Console.WriteLine(prefodd[r] ^ prefodd[l - 1]);
}
}
// Wrapper Function
static void wrapper(int[] arr, int n,
int[] l, int[] r,
int q)
{
int[] prefodd = new int[100];
int[] prefeven = new int[100];
// Evaluating prefixodd
// and prefixeven
for (int i = 1; i <= n; i++) {
if ((i) % 2 == 0) {
prefeven[i] = arr[i - 1] ^ prefeven[i - 1];
prefodd[i] = prefodd[i - 1];
}
else {
prefeven[i] = prefeven[i - 1];
prefodd[i] = prefodd[i - 1] ^ arr[i - 1];
}
}
1699
Chapter 275. Queries on XOR of XORs of all subarrays
int j = 0;
while (j != q) {
ansQueries(prefeven, prefodd,
l[j], r[j]);
j++;
}
}
/* Driver program to test above function */
public static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
int[] l = { 1, 1, 2 };
int[] r = { 2, 3, 4 };
int q = l.Length;
wrapper(arr, n, l, r, q);
}
}
// This code is contributed by vt_m.
PHP
<?php
// php Program to answer
// queries on XOR of XORs
// of all subarray
// Output for each query
function ansQueries($prefeven, $prefodd,
$l, $r)
{
// If number of element is even.
if (($r - $l + 1) % 2 == 0)
{
echo "0";
}
// If number of element is odd.
else {
1700
Chapter 275. Queries on XOR of XORs of all subarrays
// if l is even
if ($l % 2 == 0)
echo ($prefeven[$r] ^
$prefeven[$l - 1]);
// if l is odd
else
echo ($prefodd[$r] ^
$prefodd[$l - 1]);
}
echo "\n";
}
// Wrapper Function
function wrapper(array $arr, $n, array $l,
array $r, $q)
{
$prefodd=array_fill(0,100,0);
$prefeven=array_fill(0,100,0);
// Evaluating prefixodd
// and prefixeven
for ($i = 1; $i <= $n; $i++)
{
if (($i) % 2 == 0)
{
$prefeven[$i] = $arr[$i - 1] ^
$prefeven[$i - 1];
$prefodd[$i] = $prefodd[$i - 1];
}
else {
$prefeven[$i] = $prefeven[$i - 1];
$prefodd[$i] = $prefodd[$i - 1] ^
$arr[$i - 1];
}
}
$i = 0;
while ($i != $q) {
ansQueries($prefeven, $prefodd,
$l[$i], $r[$i]);
$i++;
}
}
// Driver code
$arr = array ( 1, 2, 3, 4, 5 );
1701
Chapter 275. Queries on XOR of XORs of all subarrays
Output:
0
2
6
Source
https://www.geeksforgeeks.org/queries-on-xor-of-xors-of-all-subarrays/
1702
Chapter 276
Input : n = 43, m = 8
Output : Quotient = 5, Remainder = 3
Input : n = 58, m = 16
Output : Quotient = 3, Remainder = 10
In this we are using bitwise representation of a number for understanding the role of division
of any number by divisor of form 2^k. All numbers which are power of two includes only 1
set bits in their representation and we will use this property.
For finding remainder we will take logical AND of the dividend (n) and divisor minus 1
(m-1), this will give only the set bits of dividend right to the set bit of divisor which is our
actual remainder in that case.
Further, the left part of the dividend (from the position of set bit in divisor) would be
considered for quotient. So, from dividend (n) removing all bits right from the position of
set bit of divisor will result into quotient, and right shifting the dividend log2(m) times will
do this job for finding the quotient.
Note : Log2(m) will give the number of bits present in the binary representation of m.
1703
Chapter 276. Quotient and remainder dividing by 2^k (a power of 2)
C++
Java
1704
Chapter 276. Quotient and remainder dividing by 2^k (a power of 2)
Python 3
1705
Chapter 276. Quotient and remainder dividing by 2^k (a power of 2)
# driver program
n = 43
m = 8
divide(n, m)
# This code is contributed by
# Smitha
C#
PHP
<?php
// PHP Code to find remainder
// and quotient
1706
Chapter 276. Quotient and remainder dividing by 2^k (a power of 2)
Output:
Remainder = 3
Quotient = 5
Source
https://www.geeksforgeeks.org/quotient-remainder-dividing-2k-power-2/
1707
Chapter 277
Simple solution to this problem is to run a loop from L to R and count number of set bits
in a Range. This solution take O(nlog(s)) ( where s is bits size ) for each query.
Efficient solution is based on the fact that if we store count of all set bits of numbers
in an array “BitCounts”, then we answer each query in O(1) time. So, start traversing
1708
Chapter 277. Range query for count of set bits
the elements of array and count set bits for each element and store in array. Now, find
cumulative sum of this array. This array will help in answering queries.
C++
1709
Chapter 277. Range query for count of set bits
}
// store cumulative sum of bits
for (int i = 1; i < n; i++)
BitCount[i] += BitCount[i - 1];
}
// Function to process queries
void Query(int Q[][2], int q)
{
for (int i = 0; i < q; i++)
cout << (BitCount[Q[i][1]] -
BitCount[Q[i][0] - 1]) << endl;
}
// Driver Code
int main()
{
int Arr[] = { 1, 5, 6, 10, 9, 4, 67 };
int n = sizeof(Arr) / sizeof(Arr[0]);
fillSetBitsMatrix(Arr, n);
int q = 2;
int Q[2][2] = { { 1, 5 }, { 2, 6 } };
Query(Q, q);
return 0;
}
Java
1710
Chapter 277. Range query for count of set bits
C#
1711
Chapter 277. Range query for count of set bits
1712
Chapter 277. Range query for count of set bits
fillSetBitsMatrix(Arr, n);
int q = 2;
int [,]Q = { { 1, 5 }, { 2, 6 } };
Query(Q, q);
}
}
// This code is contributed by anuj_67.
Output:
9
10
Source
https://www.geeksforgeeks.org/range-query-for-count-of-set-bits/
1713
Chapter 278
Approach: The idea is to use bits of a counter variable to mark the presence of a character
in the string. To mark the presence of ‘a’ set 0th bit as 1, for ‘b’ set 1st bit as 1 and so on.
If the corresponding bit of character present in original string is set to 0, it means it is the
first occurrence of that character, hence set its corresponding bit as 1 and keep on including
the current character in resultant string.
• character: ‘g’
x = 6(ascii of g – 97)
6th bit in counter is unset resulting first occurrence of character ‘g’.
str[0] = ‘g’
counter = 00000000000000000000000001000000 // mark 6th bit as visited
length = 1
1714
Chapter 278. Remove duplicates from a string in O(1) extra space
• character: ‘e’
x = 4(ascii of e – 97)
4th bit in counter is unset resulting in first occurrence of character ‘e’.
str[1] = ‘e’
counter = 00000000000000000000000001010000 //mark 4th bit as visited
length = 2
• character: ‘e’
x = 4(ascii of e – 97)
4th bit in counter is set resulting in duplicate character.
Ignore this character. Move for next character.
counter = 00000000000000000000000001010000 //same as previous
length = 2
• character: ‘k’
x = 10(ascii of k – 97)
10th bit in counter is unset resulting in first occurrence of character ‘k’.
str[2] = ‘k’
counter = 00000000000000000000010001010000 //mark 10th bit as visited
length = 3
Algorithm:
1715
Chapter 278. Remove duplicates from a string in O(1) extra space
{
// keeps track of visited characters
int counter = 0;
int i = 0;
int size = str.size();
// gets character value
int x;
// keeps track of length of resultant string
int length = 0;
while (i < size) {
x = str[i] - 97;
// check if Xth bit of counter is unset
if ((counter & (1 << x)) == 0) {
str[length] = 'a' + x;
// mark current character as visited
counter = counter | (1 << x);
length++;
}
i++;
}
return str.substr(0, length);
}
// Driver program to test above function
int main()
{
string str = "geeksforgeeks";
cout << removeDuplicatesFromString(str);
return 0;
}
Output:
geksfor
1716
Chapter 278. Remove duplicates from a string in O(1) extra space
Source
https://www.geeksforgeeks.org/remove-duplicates-from-a-string-in-o1-extra-space/
1717
Chapter 279
Input : 11
Output : 13
(11)10 = (1011)2.
After reversing the bits we get:
(1101)2 = (13)10.
Input : 10
Output : 5
(10)10 = (1010)2.
After reversing the bits we get:
(0101)2 = (101)2
= (5)10.
In this approach, one by one bits in binary representation of n are being obtained with the
help of bitwise right shift operation and they are being accumulated in rev with the help
of bitwise left shift operation.
Algorithm:
1718
Chapter 279. Reverse actual bits of the given number
C++
1719
Chapter 279. Reverse actual bits of the given number
{
unsigned int n = 11;
cout << reverseBits(n);
return 0;
}
Java
1720
Chapter 279. Reverse actual bits of the given number
Python 3
C#
// C# implementation to
// reverse bits of a number
using System;
class GFG
{
// function to reverse bits of a number
public static int reverseBits(int n)
{
1721
Chapter 279. Reverse actual bits of the given number
int rev = 0;
// traversing bits of 'n'
// from the right
while (n > 0)
{
// bitwise left shift
// 'rev' by 1
rev <<= 1;
// if current bit is '1'
if ((int)(n & 1) == 1)
rev ^= 1;
// bitwise right shift
//'n' by 1
n >>= 1;
}
// required number
return rev;
}
// Driver code
public static void Main()
{
int n = 11;
Console.WriteLine(reverseBits(n));
}
}
// This code is contributed
// by vt_m.
PHP
<?php
// PHP implementation to reverse
// bits of a number
// function to reverse
// bits of a number
function reverseBits($n)
{
$rev = 0;
// traversing bits of 'n'
// from the right
while ($n > 0)
1722
Chapter 279. Reverse actual bits of the given number
{
// bitwise left shift
// 'rev' by 1
$rev <<= 1;
// if current bit is '1'
if ($n & 1 == 1)
$rev ^= 1;
// bitwise right shift
// 'n' by 1
$n >>= 1;
}
// required number
return $rev;
}
// Driver code
$n = 11;
echo reverseBits($n);
// This code is contributed by mits
?>
Output :
13
Time Complexity: O(num), where num is the number of bits in the binary representation
of n.
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/reverse-actual-bits-given-number/
1723
Chapter 280
Reverse an array without using subtract sign ‘-‘ anywhere in the code - GeeksforGeeks
Given an array, the task is to reverse the array without using subtract sign ‘-‘ anywhere in
your code. It is not tough to reverse an array but the main thing is to note use ‘-‘ operator.
Asked in: Moonfrog Interview
Below are different approaches:
Method 1:
1- Store array elements into a vector in C++.
2- Then reverse the vector using predefined functions.
3- Then store reversed elements into the array back.
Method 2:
1- Store array elements into a stack.
2- As the stack follows Last In First Out, so we can store elements from
top of the stack into the array which will be itself in a reverse manner.
Method 3:
1- In this method the idea is to use negative sign but by storing it into a variable.
2- By using this statement x = (INT_MIN/INT_MAX), we get -1 in a variable x.
3- As INT_MIN and INT_MAX have same values just of opposite signs,so on dividing
them it will give -1.
4- Then ‘x’ can be used in decrementing the index from last.
1724
Chapter 280. Reverse an array without using subtract sign ‘-‘ anywhere in the code
// Function to reverse array
void reverseArray(int arr[], int n)
{
// Trick to assign -1 to a variable
int x = (INT_MIN/INT_MAX);
// Reverse array in simple manner
for (int i = 0; i<n/2 ; i++)
// Swap ith index value with (n-i-1)th
// index value
swap(arr[i], arr[n + (x*i) + x]);
}
//Drivers code
int main()
{
int arr[] = {5, 3, 7, 2, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, n);
// print the reversed array
for (int i=0; i< n ; i++)
cout << arr[i] << " ";
return 0;
}
Output:
6 1 2 7 3 5
Method 4:
In this method 4, the idea is to use bitwise operator to implement subtraction i.e.
A – B = A + ~B + 1
so, i– can be written as i = i +~1 +1
1725
Chapter 280. Reverse an array without using subtract sign ‘-‘ anywhere in the code
{
int x = (INT_MIN/INT_MAX);
// Reverse array in simple manner
for (int i = 0; i<n/2 ; i++)
// Swap ith index value with (n-i-1)th
// index value
// Note : A - B = A + ~B + 1
// So n - i = n + ~i + 1 then
// n - i - 1 = (n + ~i + 1) + ~1 + 1
swap(arr[i], arr[(n + ~i + 1) + ~1 + 1]);
}
// Driver code
int main()
{
int arr[] = {5, 3, 7, 2, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, n);
// print the reversed array
for (int i=0; i< n ; i++)
cout << arr[i] << " ";
return 0;
}
Output:
6 1 2 7 3 5
Source
https://www.geeksforgeeks.org/reverse-array-without-using-subtract-sign-anywhere-code/
1726
Chapter 281
Input : n = 1
Output : 2147483648
On a machine with size of unsigned
bit as 32. Reverse of 0....001 is
100....0.
Input : n = 2147483648
Output : 1
In the previous post we had seen two method that solved this problem in O(n) & O(logn )
time. Here we solve this problem in O(1) time using lookup table. It’s hard to reverse all
32 bits (assuming this as size of int) in one go using lookup table (” because it’s infeasible
to create lookup table of size 232 -1 “). So we break 32 bits into 8 bits of chunks( lookup
table of size 28 -1 “0-255”).
Lookup Table
in lookup tale we will store reverse of every number that are in a range( 0-255)
LookupTable[0] = 0 | binary 00000000 Reverse 00000000
LookupTable[1] = 128 | binary 00000001 reverse 10000000
LookupTable[2] = 64 | binary 00000010 reverse 01000000
LookupTanle[3] = 192 | binary 00000011 reverse 11000000
LookupTable[4] = 32 | binary 00000100 reverse 00100000
and so on… upto lookuptable[255].
1727
Chapter 281. Reverse bits using lookup table in O(1) time
Now Binary :
00000000 | 00000000 | 00001100 | 00010101
1728
Chapter 281. Reverse bits using lookup table in O(1) time
return reverse_num;
}
//driver program to test above function
int main()
{
int x = 12456;
printf("%u", reverseBits(x));
return 0;
}
Output:
353107968
Source
https://www.geeksforgeeks.org/reverse-bits-using-lookup-table-in-o1-time/
1729
Chapter 282
#include<stdio.h>
#define INT_BITS 32
/*Function to left rotate n by d bits*/
int leftRotate(int n, unsigned int d)
{
/* In n<<d, last d bits are 0. To put first 3 bits of n at
last, do bitwise or of n<<d with n >>(INT_BITS - d) */
return (n << d)|(n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)
{
/* In n>>d, first d bits are 0. To put last 3 bits of at
1730
Chapter 282. Rotate bits of a number
Java
1731
Chapter 282. Rotate bits of a number
int d = 2;
System.out.print("Left Rotation of " + n +
" by " + d + " is ");
System.out.print(leftRotate(n, d));
System.out.print("\nRight Rotation of " + n +
" by " + d + " is ");
System.out.print(rightRotate(n, d));
}
}
// This code is contributed by Anant Agarwal.
Python3
1732
Chapter 282. Rotate bits of a number
print("Right Rotation of",n,"by"
,d,"is",end=" ")
print(rightRotate(n, d))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to rotate
// bits of a number
using System;
class GFG
{
static int INT_BITS = 32;
/* Function to left rotate n by d bits*/
static int leftRotate(int n, int d) {
/* In n<<d, last d bits are 0.
To put first 3 bits of n at
last, do bitwise or of n<<d with
n >>(INT_BITS - d) */
return (n << d) | (n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
static int rightRotate(int n, int d) {
/* In n>>d, first d bits are 0.
To put last 3 bits of at
first, do bitwise or of n>>d
with n <<(INT_BITS - d) */
return (n >> d) | (n << (INT_BITS - d));
}
// Driver code
public static void Main()
{
int n = 16;
int d = 2;
Console.Write("Left Rotation of " + n
+ " by " + d + " is ");
Console.Write(leftRotate(n, d));
1733
Chapter 282. Rotate bits of a number
Output :
Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4
Source
https://www.geeksforgeeks.org/rotate-bits-of-an-integer/
1734
Chapter 283
C/C++
#include <iostream>
using namespace std;
// A method to multiply two numbers using Russian Peasant method
unsigned int russianPeasant(unsigned int a, unsigned int b)
{
1735
Chapter 283. Russian Peasant (Multiply two numbers using bitwise operators)
Java
1736
Chapter 283. Russian Peasant (Multiply two numbers using bitwise operators)
a = a << 1;
b = b >> 1;
}
return res;
}
// driver program
public static void main (String[] args)
{
System.out.println(russianPeasant(18, 1));
System.out.println(russianPeasant(20, 12));
}
}
// Contributed by Pramod Kumar
Python 3
1737
Chapter 283. Russian Peasant (Multiply two numbers using bitwise operators)
print(russianPeasant(20, 12))
# This code is contributed by
# Smitha Dinesh Semwal
C#
PHP
<?php
1738
Chapter 283. Russian Peasant (Multiply two numbers using bitwise operators)
Output:
18
240
1739
Chapter 283. Russian Peasant (Multiply two numbers using bitwise operators)
Reference:
http://mathforum.org/dr.math/faq/faq.peasant.html
This article is compiled by Shalki Agarwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Smitha Dinesh Semwal, jit_t
Source
https://www.geeksforgeeks.org/russian-peasant-multiply-two-numbers-using-bitwise-operators/
1740
Chapter 284
Input : 8
Output :3
Explanation: Binary representation of
8 : 1000, so number of set bits in 8 is 1.
So the integers less than 8 with same number
of set bits are : 4, 2, 1
Input :1
Output :0
Input :4
Output :2
Approach:
1. Using __builtin_popcount() inbuilt function, count set bits in N and store into a
temp variable
2. Iterate from n-1 to 1 and also count set bits in i using __builtin_popcount()
function
3. Now, compare temp with __builtin_popcount(i)
4. If both are equal then increment counter variable
5. Return counter
1741
Chapter 284. Same Number Of Set Bits As N
C++
Java
1742
Chapter 284. Same Number Of Set Bits As N
{
d = n % 2;
n = n / 2;
if(d == 1)
t++;
}
return t;
}
static int smallerNumsWithSameSetBits(int n)
{
// __builtin_popcount function that count
// set bits in n
int temp = __builtin_popcount(n);
// Iterate from n-1 to 1
int count = 0;
for (int i = n - 1; i > 0; i--) {
// check if the number of set bits
// equals to temp increment count
if (temp == __builtin_popcount(i))
count++;
}
return count;
}
// Driver Code
public static void main(String[] args)
{
int n = 4;
System.out.println(
smallerNumsWithSameSetBits(n));
}
}
// This code is contributed by Arnab Kundu.
Python3
1743
Chapter 284. Same Number Of Set Bits As N
if(d == 1) :
t = t + 1
return t
def smallerNumsWithSameSetBits(n) :
# __builtin_popcount function
# that count set bits in n
temp = __builtin_popcount(n)
# Iterate from n-1 to 1
count = 0
for i in range(n-1,0,-1) :
# check if the number of
# set bits equals to temp
# increment count
if (temp == __builtin_popcount(i)) :
count = count + 1
return count
# Driver Code
n = 4
print (smallerNumsWithSameSetBits(n))
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
1744
Chapter 284. Same Number Of Set Bits As N
return t;
}
static int smallerNumsWithSameSetBits(int n)
{
// __builtin_popcount function that count
// set bits in n
int temp = __builtin_popcount(n);
// Iterate from n-1 to 1
int count = 0;
for (int i = n - 1; i > 0; i--) {
// check if the number of set bits
// equals to temp increment count
if (temp == __builtin_popcount(i))
count++;
}
return count;
}
// Driver Code
static public void Main(String []args)
{
int n = 4;
Console.WriteLine(
smallerNumsWithSameSetBits(n));
}
}
// This code is contributed by Arnab Kundu.
PHP
<?php
// PHP program to find numbers
// less than N that have same
// Number Of Set Bits As N
function __builtin_popcount($n)
{
$t = 0;
while($n > 0)
{
$d = $n % 2;
$n = intval($n / 2);
if($d == 1)
$t++;
}
1745
Chapter 284. Same Number Of Set Bits As N
return $t;
}
function smallerNumsWithSameSetBits($n)
{
// __builtin_popcount function
// that count set bits in n
$temp = __builtin_popcount($n);
// Iterate from n-1 to 1
$count = 0;
for ($i = $n - 1; $i > 0; $i--)
{
// check if the number of
// set bits equals to temp
// increment count
if ($temp == __builtin_popcount($i))
$count++;
}
return $count;
}
// Driver Code
$n = 4;
echo (smallerNumsWithSameSetBits($n));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
Source
https://www.geeksforgeeks.org/number-set-bits-n/
1746
Chapter 285
Input : 20
Output : 30
Binary representation of 20 is
10100. After setting
even bits, we get 11110
Input : 10
Output : 10
Method 1:-
1. First generate a number that contains even position bits.
2. Take OR with the original number. Note that 1 | 1 = 1 and 1 | 0 = 1.
Let’s understand this approach with below code.
C++
1747
Chapter 285. Set all even bits of a number
int evenbitsetnumber(int n)
{
// Generate 101010...10 number and
// store in res.
int count = 0, res = 0;
for (int temp = n; temp > 0; temp >>= 1) {
// if bit is even then generate
// number and or with res
if (count % 2 == 1)
res |= (1 << count);
count++;
}
// return OR number
return (n | res);
}
int main()
{
int n = 10;
cout << evenbitsetnumber(n);
return 0;
}
Java
1748
Chapter 285. Set all even bits of a number
// return OR number
return (n | res);
}
// Driver code
public static void main(String[] args)
{
int n = 4;
System.out.println(evenbitsetnumber(n));
}
}
// This code is contributed
// by prerna saini.
Python3
1749
Chapter 285. Set all even bits of a number
C#
PHP
<?php
// Simple php program to set
// all even bits of a number
1750
Chapter 285. Set all even bits of a number
// Sets even bits of n and
// returns modified number.
function evenbitsetnumber($n)
{
// Generate 101010...10 number
// and store in res.
$count = 0;
$res = 0;
for ($temp = $n; $temp > 0; $temp >>= 1)
{
// if bit is even then generate
// number and or with res
if ($count % 2 == 1)
$res |= (1 << $count);
$count++;
}
// return OR number
return ($n | $res);
}
//Driver Code
$n = 10;
echo evenbitsetnumber($n);
//This Code is contributed by mits
?>
Output:
10
C++
1751
Chapter 285. Set all even bits of a number
int getmsb(int n)
{
// set all bits
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// return msb
// increment n by 1
// and shift by 1
return (n + 1) >> 1;
}
// return even seted number
int getevenbits(int n)
{
// get msb here
n = getmsb(n);
// generate even bits like 101010..
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// if bits is odd then shift by 1
if (n & 1)
n = n >> 1;
// return even set bits number
return n;
}
// set all even bits here
int setallevenbits(int n)
{
// take or with even set bits number
return n | getevenbits(n);
}
int main()
{
int n = 10;
cout << setallevenbits(n);
1752
Chapter 285. Set all even bits of a number
return 0;
}
Java
1753
Chapter 285. Set all even bits of a number
Python3
# Efficient Python 3
# program to set all even
# bits of a number
# return msb set number
def getmsb(n):
# set all bits
n |= n >> 1
n |= n >> 2
n |= n >> 4
n |= n >> 8
n |= n >> 16
# return msb
# increment n by 1
# and shift by 1
return (n + 1) >> 1
# return even seted number
def getevenbits(n):
1754
Chapter 285. Set all even bits of a number
C#
1755
Chapter 285. Set all even bits of a number
// return msb
// increment n by 1
// and shift by 1
return (n + 1) >> 1;
}
// return even seted number
static int getevenbits(int n)
{
// get msb here
n = getmsb(n);
// generate even
// bits like 101010..
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// if bits is odd
// then shift by 1
if ((n & 1) == 1)
n = n >> 1;
// return even
// set bits number
return n;
}
// set all even bits here
static int setallevenbits(int n)
{
// take or with even
// set bits number
return n | getevenbits(n);
}
// Driver Code
public static void Main ()
{
int n = 10;
Console.WriteLine(setallevenbits(n));
}
}
1756
Chapter 285. Set all even bits of a number
PHP
<?php
// Efficient php program to set
// all even bits of a number
// return msb set number
function getmsb($n)
{
// set all bits
$n |= $n >> 1;
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
// return msb
// increment n by 1
// and shift by 1
return ($n + 1) >> 1;
}
// return even seted number
function getevenbits($n)
{
// get msb here
$n = getmsb($n);
// generate even bits
// like 101010..
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
// if bits is odd then
// shift by 1
if ($n & 1)
$n = $n >> 1;
// return even set
// bits number
return $n;
}
1757
Chapter 285. Set all even bits of a number
// set all even bits here
function setallevenbits($n)
{
// take or with even
// set bits number
return $n | getevenbits($n);
}
//Driver code
$n = 10;
echo setallevenbits($n);
//This code is contributed by mits
?>
Output:
10
Source
https://www.geeksforgeeks.org/set-all-even-bits-of-a-number/
1758
Chapter 286
Input : 20
Output : 21
Explanation : Binary representation of 20
is 10100. Setting all odd
bits make the number 10101 which is binary
representation of 21.
Input : 10
Output : 15
C++
1759
Chapter 286. Set all odd bits of a number
// set all odd bit
int oddbitsetnumber(int n)
{
int count = 0;
// res for store 010101.. number
int res = 0;
// generate number form of 010101.....till
// temp size
for (int temp = n; temp > 0; temp >>= 1) {
// if bit is odd, then generate
// number and or with res
if (count % 2 == 0)
res |= (1 << count);
count++;
}
return (n | res);
}
// Driver code
int main()
{
int n = 10;
cout << oddbitsetnumber(n);
return 0;
}
Java
1760
Chapter 286. Set all odd bits of a number
Python3
1761
Chapter 286. Set all odd bits of a number
count += 1
temp >>= 1
return (n | res)
n = 10
print (oddbitsetnumber(n))
#This code is contributed by Shreyanshi Arun.
C#
1762
Chapter 286. Set all odd bits of a number
}
}
// This code is contributed
// by prerna ajit
PHP
<?php
// php code Set all odd
// bits of a number
// set all odd bit
function oddbitsetnumber($n)
{
$count = 0;
// res for store 010101..
// number
$res = 0;
// generate number form of
// 010101... till temp size
for ($temp = $n; $temp > 0; $temp >>= 1)
{
// if bit is odd, then generate
// number and or with res
if ($count % 2 == 0)
$res |= (1 << $count);
$count++;
}
return ($n | $res);
}
// Driver code
$n = 10;
echo oddbitsetnumber($n);
// This code is contributed by mits
?>
Output:
15
1763
Chapter 286. Set all odd bits of a number
C++
1764
Chapter 286. Set all odd bits of a number
{
// take OR with odd set bits number
return n | getevenbits(n);
}
// Driver code
int main()
{
int n = 10;
cout << setalloddbits(n);
return 0;
}
Java
1765
Chapter 286. Set all odd bits of a number
Python3
1766
Chapter 286. Set all odd bits of a number
C#
1767
Chapter 286. Set all odd bits of a number
1768
Chapter 286. Set all odd bits of a number
{
int n = 10;
Console.WriteLine(setalloddbits(n));
}
}
// This code is contributed ajit
PHP
<?php
// Efficient php program to
// set all odd bits number
// return MSB set number
function getmsb($n)
{
// set all bits
// including MSB.
$n |= $n >> 1;
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
// return MSB
return ($n + 1) >> 1;
}
// Returns a number of
// same size (MSB at
// same position) as n
// and all odd bits set
function getevenbits($n)
{
$n = getmsb($n);
// generate odd bits
// like 010101..
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
// if bits is even
// then shift by 1
if (($n&1) == 0)
1769
Chapter 286. Set all odd bits of a number
$n = $n >> 1;
// return odd set
// bits number
return $n;
}
// set all odd bits here
function setalloddbits($n)
{
// take OR with odd
// set bits number
return $n | getevenbits($n);
}
// Driver code
$n = 10;
echo setalloddbits($n);
// This code is contributed by mits
?>
Output:
15
Source
https://www.geeksforgeeks.org/set-odd-bits-number/
1770
Chapter 287
Input : n = 17, l = 2, r = 3
Output : 23
(17)10 = (10001)2
(23)10 = (10111)2
The bits in the range 2 to 3 in the binary
representation of 17 are set.
Input : n = 50, l = 2, r = 5
Output : 62
1771
Chapter 287. Set all the bits in given range of a number
C++
Java
1772
Chapter 287. Set all the bits in given range of a number
Python3
C#
// C# implementation to Set
1773
Chapter 287. Set all the bits in given range of a number
PHP
<?php
// PHP implementation to Set
// bits in the given range
// function to toggle bits
// in the given range
function setallbitgivenrange($n, $l, $r)
{
// calculating a number 'range'
// having set bits in the range
// from l to r and all other
// bits as 0 (or unset).
$range = (((1 << ($l - 1)) - 1) ^
((1 << ($r)) - 1));
1774
Chapter 287. Set all the bits in given range of a number
Output :
23
Improved By : Sam007
Source
https://www.geeksforgeeks.org/set-bits-given-range-number/
1775
Chapter 288
Input : N = 1, M = 2, i = 2, j = 4
Output: 9
N = 00000001(Considering 8 bits only)
M = 10 (Binary of 2) For more indexes,
leading zeroes will be considered.
Now set 3 bits from ith index to j in
the N as in the M.
Bits:- 0 0 0 (0 1 0) 0 1 = 9
Indexes:- 7 6 5 4 3 2 1 0
From index 2 to 4, bits are set according
to the M.
Asked in : Adobe
A simple solution is to traverse all bits in N from 0 to 31 and set the bits equals to M in
the range from i to j.
An efficient solution is to do following steps.
1776
Chapter 288. Set bits in N equals to M in the given range.
C++
1777
Chapter 288. Set bits in N equals to M in the given range.
Java
// Java Program
public class GFG
{
// Function to set the bits
static int setBits(int n, int m, int i, int j)
{
// number with all 1's
int allOnes = ~0;
// Set all the bits in the left of j
int left = allOnes << (j + 1);
// Set all the bits in the right of j
int right = ((1 << i) - 1);
// Do Bitwise OR to get all the bits
// set except in the range from i to j
int mask = left | right;
// clear bits j through i
int masked_n = n & mask;
// move m into the correct position
int m_shifted = m << i;
// return the Bitwise OR of masked_n
// and shifted_m
return (masked_n | m_shifted);
}
// Driver Program to test above function
public static void main(String[] args)
{
int n = 2, m = 4;
int i = 2, j = 4;
System.out.println(setBits(n, m, i, j));
}
}
// This code is contributed by Sumit Ghosh
Python
1778
Chapter 288. Set bits in N equals to M in the given range.
# Function to set the bits
def setBits(n, m, i, j):
# number with all 1's
allOnes = not 0
# Set all the bits in the left of j
left = allOnes << (j + 1)
# Set all the bits in the right of j
right = ((1 << i) - 1)
# Do Bitwsie OR to get all the bits
# set except in the range from i to j
mask = left | right
# clear bits j through i
masked_n = n & mask
# move m into the correct position
m_shifted = m << i
# return the Bitwise OR of masked_n
# and shifted_m
return (masked_n | m_shifted)
# Drivers program
n, m = 2, 4
i, j = 2, 4
print setBits(n, m, i, j)
# This code is submitted by Sachin Bisht
C#
1779
Chapter 288. Set bits in N equals to M in the given range.
PHP
<?php
// PHP program for above implementation
// Function to set the bits
function setBits($n, $m, $i, $j)
{
// number with all 1's
$allOnes = ~0;
// Set all the bits
// in the left of j
$left = $allOnes << ($j + 1);
1780
Chapter 288. Set bits in N equals to M in the given range.
Output :
18
Reference:
https://www.careercup.com/question?id=8863294
Improved By : jit_t
Source
https://www.geeksforgeeks.org/set-bits-n-equals-m-given-range/
1781
Chapter 289
Input : n = 10, k = 2
Output : 14
(10)10 = (1010)2
Now, set the 2nd bit from right.
(14)10 = (1110)2
2nd bit has been set.
Input : n = 15, k = 3
Output : 15
3rd bit of 15 is already set.
To set any bit we use bitwise OR | operator. As we already know bitwise OR | operator
evaluates each bit of the result to 1 if any of the operand’s corresponding bit is set (1).
In-order to set kth bit of a number we need to shift 1 k times to its left and then perform
bitwise OR operation with the number and result of left shift performed just before.
In general, (1 << k) | n.
C++
1782
Chapter 289. Set the K-th bit of a given number
Java
Python3
1783
Chapter 289. Set the K-th bit of a given number
# Python implementation
# to set the kth bit
# of the given number
# function to set
# the kth bit
def setKthBit(n,k):
# kth bit of n is being
# set by this operation
return ((1 << k) | n)
# Driver code
n = 10
k = 2
print("Kth bit set number = ",
setKthBit(n, k))
# This code is contributed
# by Anant Agarwal.
C#
1784
Chapter 289. Set the K-th bit of a given number
// This code is contributed by
// Smitha Dinesh Semwal.
PHP
<?php
// PHP implementation to
// set the kth bit of
// the given number
// function to set
// the kth bit
function setKthBit($n, $k)
{
// kth bit of n is being
// set by this operation
return ((1 << $k) | $n);
}
// Driver Code
$n = 10; $k = 2;
echo "Kth bit set number = ",
setKthBit($n, $k);
// This code is contributed by m_kit
?>
Output:
Source
https://www.geeksforgeeks.org/set-k-th-bit-given-number/
1785
Chapter 290
Input : 10
Output : 14
10 = 1 0 1 0 // 10 binary
14 = 1 1 1 0 // after set left most unset bit
Input : 15
Output : 15
15 = 1 1 1 1 // 15 binary
15 = 1 1 1 1 // because all bits are set
Approach:-
1. Return the number if all bits are set.
2. Traverse all the bit to get the last unset bit.
3. Take OR with the original number and the unset bit.
Below is the implementation of the approach.
C++
1786
Chapter 290. Set the Left most unset bit
Java
1787
Chapter 290. Set the Left most unset bit
Python3
1788
Chapter 290. Set the Left most unset bit
# return OR of number and
# unset bit pos
return (n | (1 << (pos)))
# Driver Function
n = 10
print(setleftmostunsetbit(n))
# This code is contributed by Ansu Kumari
C#
// C# program to set
// the leftmost unset bit
using System;
class GFG
{
// set left most unset bit
static int setleftmostunsetbit(int n)
{
// if number contain all
// 1 then return n
if ((n & (n + 1)) == 0)
return n;
// Find position of leftmost unset bit.
int pos = 0;
for (int temp = n, count = 0; temp > 0;
temp >>= 1, count++)
// if temp L.S.B is zero
// then unset bit pos is
// change
if ((temp & 1) == 0)
pos = count;
// return OR of number and
// unset bit pos
return (n | (1 << (pos)));
}
// Driver Function
public static void Main ()
{
int n = 10;
1789
Chapter 290. Set the Left most unset bit
Console.WriteLine(setleftmostunsetbit(n));
}
}
// This code is contributed by vt_m
PHP
<?php
// php program to set the
// leftmost unset bit
// set left most unset bit
function setleftmostunsetbit($n)
{
// if number contain all
// 1 then return n
if (($n & ($n + 1)) == 0)
return $n;
// Find position of leftmost
// unset bit.
$pos = 0;
for ($temp = $n, $count = 0; $temp > 0;
$temp >>= 1, $count++)
// if temp L.S.B is zero
// then unset bit pos is
// change
if (($temp & 1) == 0)
$pos = $count;
// return OR of number
// and unset bit pos
return ($n | (1 << ($pos)));
}
// Driver code
$n = 10;
echo setleftmostunsetbit($n);
//This code is contributed by mits
?>
Output:
1790
Chapter 290. Set the Left most unset bit
14
Source
https://www.geeksforgeeks.org/set-left-unset-bit/
1791
Chapter 291
Input : 21
Output : 23
(21)10 = (10101)2
Rightmost unset bit is at position 2(from right) as
highlighted in the binary representation of 21.
(23)10 = (10111)2
The bit at position 2 has been set.
Input : 15
Output : 15
1. If n = 0, return 1.
2. If all bits of n are set, return n. Refer this post.
3. Else perform bitwise not on the given number(operation equivalent to 1’s complement).
Let it be num = ~n.
4. Get the position of rightmost set bit of num. Let the position be pos.
5. Return (1 << (pos – 1)) | n.
C++
1792
Chapter 291. Set the rightmost unset bit
#include <bits/stdc++.h>
using namespace std;
// function to find the position
// of rightmost set bit
int getPosOfRightmostSetBit(int n)
{
return log2(n&-n)+1;
}
int setRightmostUnsetBit(int n)
{
// if n = 0, return 1
if (n == 0)
return 1;
// if all bits of 'n' are set
if ((n & (n + 1)) == 0)
return n;
// position of rightmost unset bit in 'n'
// passing ~n as argument
int pos = getPosOfRightmostSetBit(~n);
// set the bit at position 'pos'
return ((1 << (pos - 1)) | n);
}
// Driver program to test above
int main()
{
int n = 21;
cout << setRightmostUnsetBit(n);
return 0;
}
Java
1793
Chapter 291. Set the rightmost unset bit
}
static int setRightmostUnsetBit(int n)
{
// if n = 0, return 1
if (n == 0)
return 1;
// if all bits of 'n' are set
if ((n & (n + 1)) == 0)
return n;
// position of rightmost unset bit in 'n'
// passing ~n as argument
int pos = getPosOfRightmostSetBit(~n);
// set the bit at position 'pos'
return ((1 << (pos - 1)) | n);
}
// Driver code
public static void main(String arg[]) {
int n = 21;
System.out.print(setRightmostUnsetBit(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python implementation to
# set the rightmost unset bit
import math
# function to find the position
# of rightmost set bit
def getPosOfRightmostSetBit(n):
return int(math.log2(n&-n)+1)
def setRightmostUnsetBit(n):
# if n = 0, return 1
if (n == 0):
return 1
1794
Chapter 291. Set the rightmost unset bit
Output:
23
Source
https://www.geeksforgeeks.org/set-rightmost-unset-bit/
1795
Chapter 292
Method 1 : We can simply simulate the whole process and find the exact order of the
cards after all the N shuffles are done.
Time Complexity : O(N * 2^N)
Method 2 :
Let us try to find the binary representation of Key and the final answer and try to spot
some observations based on it.
Let N = 3
Below is the table :
Key ANS
000 000
1796
Chapter 292. Shuffle a pack of cards and answer the query
001 100
010 010
011 110
100 001
101 101
110 011
111 111
It is clearly visible that the answer is the reverse of binary representation of Key.
C++
1797
Chapter 292. Shuffle a pack of cards and answer the query
Java
Python3
1798
Chapter 292. Shuffle a pack of cards and answer the query
C#
1799
Chapter 292. Shuffle a pack of cards and answer the query
}
// Printing the result
Console.Write(reverse_num);
}
//Driver code
public static void Main()
{
// No. of Shuffle Steps
int N = 3;
// Key position
int key = 3;
shuffle(N, key);
}
}
// This code is contributed by Anant Agarwal.
Output:
Source
https://www.geeksforgeeks.org/shuffle-pack-cards-answer-query/
1800
Chapter 293
Smallest number whose set bits are maximum in a given range - GeeksforGeeks
Given a positive integer ‘l‘ and ‘r‘. Find the smallest number ‘n‘ such that l <= n <=
r and count of number of set bits(number of ‘1’s in binary representation) is maximum as
possible.
Examples :
Input: 1 4
Output: 3
Explanation:
Binary representation from '1' to '4':
110 = 0012
210 = 0102
310 = 0112
110 = 1002
Thus number '3' has maximum set bits = 2
Input: 1 10
Output: 7
Simple approach is to traverse from ‘l’ to ‘r’ and count the set bits for each ‘x’(l <= n
<= r) and print the number whose count is maximum among them. Time complexity of
this approach is O(n*log(r)).
C++
1801
Chapter 293. Smallest number whose set bits are maximum in a given range
Python 3
1802
Chapter 293. Smallest number whose set bits are maximum in a given range
PHP
<?php
// PHP program to find number
// whose set bits are maximum
// among 'l' and 'r'
// Returns smallest number
// whose set bits are maximum
// in given range.
function countMaxSetBits($left, $right)
{
// Initialize the maximum
// count and final answer
// as 'num'
$max_count = -1; $num;
for ($i = $left; $i <= $right; ++$i)
1803
Chapter 293. Smallest number whose set bits are maximum in a given range
{
$temp = $i; $cnt = 0;
// Traverse for every
// bit of 'i' number
while ($temp)
{
if ($temp & 1)
++$cnt;
$temp >>= 1;
}
// If count is greater than
// previous calculated
// max_count, update it
if ($cnt > $max_count)
{
$max_count = $cnt;
$num = $i;
}
}
return $num;
}
// Driver code
$l = 1; $r = 5;
echo countMaxSetBits($l, $r), "\n";
$l = 1; $r = 10;
echo countMaxSetBits($l, $r);
// This code is contributed by m_kit
?>
Output :
3
7
Efficient approach is to use bit-manipulation. Instead of iterating for every number from
‘l’ to ‘r’, iterate only after updating the desired number(‘num’) i.e., take the bitwise ‘OR’ of
number with the consecutive number. For instance,
Let l = 2, and r = 10
1. num = 2
2. x = num OR (num + 1)
1804
Chapter 293. Smallest number whose set bits are maximum in a given range
C++
Java
1805
Chapter 293. Smallest number whose set bits are maximum in a given range
Python3
1806
Chapter 293. Smallest number whose set bits are maximum in a given range
C#
PHP
<?php
// PHP program to find number
// whose set bits are maximum
// among 'l' and 'r'
// Returns smallest number
// whose set bits are
// maximum in given range.
1807
Chapter 293. Smallest number whose set bits are maximum in a given range
function countMaxSetBits($left,
$right)
{
while (($left | ($left + 1)) <= $right)
$left |= $left + 1;
return $left;
}
// Driver code
$l = 1 ; $r = 5;
echo countMaxSetBits($l, $r) , "\n";
$l = 1; $r = 10;
echo countMaxSetBits($l, $r) ;
// This code is contributed by aj_36
?>
Output :
3
7
Source
https://www.geeksforgeeks.org/smallest-number-whose-set-bits-maximum-given-range/
1808
Chapter 294
#include<stdio.h>
int smallest(int x, int y, int z)
{
int c = 0;
while ( x && y && z )
{
x--; y--; z--; c++;
}
return c;
}
int main()
{
int x = 12, y = 15, z = 5;
printf("Minimum of 3 numbers is %d", smallest(x, y, z));
1809
Chapter 294. Smallest of three integers without comparison operators
return 0;
}
Java
class GFG{
static int smallest(int x, int y, int z)
{
int c = 0;
while ( x != 0 && y != 0 && z != 0 )
{
x--; y--; z--; c++;
}
return c;
}
public static void main(String[] args)
{
int x = 12, y = 15, z = 5;
System.out.printf("Minimum of 3" +
" numbers is %d", smallest(x, y, z));
}
}
// This code is contributed by Smitha Dinesh Semwal.
Python3
1810
Chapter 294. Smallest of three integers without comparison operators
# Driver Code
x = 12
y = 15
z = 5
print("Minimum of 3 numbers is",
smallest(x, y, z))
# This code is contributed by Anshika Goyal
C#
php
<?php
// php program to find Smallest
// of three integers without
// comparison operators
1811
Chapter 294. Smallest of three integers without comparison operators
This methid doesn’t work for negative numbers. Method 2 works for negative nnumbers
also.
Method 2 (Use Bit Operations)
Use method 2 of this post to find minimum of two numbers (We can’t use Method 1 as
Method 1 uses comparison operator). Once we have functionality to find minimum of 2
numbers, we can use this to find minimum of 3 numbers.
1812
Chapter 294. Smallest of three integers without comparison operators
#include <stdio.h>
// Using division operator to find minimum of three numbers
int smallest(int x, int y, int z)
{
if (!(y/x)) // Same as "if (y < x)"
return (!(y/z))? y : z;
return (!(x/z))? x : z;
}
int main()
{
int x = 78, y = 88, z = 68;
printf("Minimum of 3 numbers is %d", smallest(x, y, z));
return 0;
}
Improved By : Sam007
Source
https://www.geeksforgeeks.org/smallest-of-three-integers-without-comparison-operators/
1813
Chapter 295
Smallest perfect power of 2 greater than n (without using arithmetic operators) - Geeks-
forGeeks
Given a non-negative integer n. The problem is to find the smallest perfect power of 2 which
is greater than n without using the arithmetic operators.
Examples :
Input : n = 10
Output : 16
Input : n = 128
Output : 256
Algorithm :
C++
1814
Chapter 295. Smallest perfect power of 2 greater than n (without using arithmetic
operators)
// of 2 greater than n
#include <bits/stdc++.h>
using namespace std;
// Function to find smallest perfect power
// of 2 greater than n
unsigned int perfectPowerOf2(unsigned int n)
{
// To store perfect power of 2
unsigned int per_pow = 1;
while (n > 0)
{
// bitwise left shift by 1
per_pow = per_pow << 1;
// bitwise right shift by 1
n = n >> 1;
}
// Required perfect power of 2
return per_pow;
}
// Driver program to test above
int main()
{
unsigned int n = 128;
cout << "Perfect power of 2 greater than "
<< n << ": " << perfectPowerOf2(n);
return 0;
}
Java
1815
Chapter 295. Smallest perfect power of 2 greater than n (without using arithmetic
operators)
while (n > 0)
{
// bitwise left shift by 1
per_pow = per_pow << 1;
n = n >> 1;
}
// Required perfect power of 2
return per_pow;
}
// Driver program
public static void main(String[] args)
{
int n = 12;
System.out.println("Perfect power of 2 greater than "
+ n + ": " + perfectPowerOf2(n));
}
}
//This code is contributed by Arnav Kr. Mandal.
Python3
1816
Chapter 295. Smallest perfect power of 2 greater than n (without using arithmetic
operators)
n = 128
print("Perfect power of 2 greater than",
n, ":",perfectPowerOf2(n))
# This code is contributed by "Sharad_Bhardwaj".
C#
PHP
<?php
1817
Chapter 295. Smallest perfect power of 2 greater than n (without using arithmetic
operators)
Output:
Time Complexity: O(num), where num is the number of bits in the binary representation
of n.
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/smallest-perfect-power-2-greater-n-without-using-arithmetic-operators/
1818
Chapter 296
Input : n = 5
Output: 8
Input : n = 17
Output : 32
Input : n = 32
Output : 32
There are plenty of solutions for this. Let us take the example of 17 to explain some of
them.
Example :
1819
Chapter 296. Smallest power of 2 greater than or equal to n
Example :
#include<stdio.h>
unsigned int nextPowerOf2(unsigned int n)
{
unsigned count = 0;
// First n in the below condition
// is for the case where n is 0
if (n && !(n & (n - 1)))
return n;
while( n != 0)
{
n >>= 1;
count += 1;
}
1820
Chapter 296. Smallest power of 2 greater than or equal to n
return 1 << count;
}
// Driver Code
int main()
{
unsigned int n = 0;
printf("%d", nextPowerOf2(n));
return 0;
}
Java
1821
Chapter 296. Smallest power of 2 greater than or equal to n
Python3
def nextPowerOf2(n):
count = 0;
# First n in the below
# condition is for the
# case where n is 0
if (n and not(n & (n - 1))):
return n
while( n != 0):
n >>= 1
count += 1
return 1 << count;
# Driver Code
n = 0
print(nextPowerOf2(n))
# This code is contributed
# by Smitha Dinesh Semwal
C#
1822
Chapter 296. Smallest power of 2 greater than or equal to n
{
n >>= 1;
count += 1;
}
return 1 << count;
}
// Driver Code
public static void Main()
{
int n = 0;
Console.WriteLine(nextPowerOf2(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find smallest
// power of 2 greater than or
// equal to n
function nextPowerOf2($n)
{
$count = 0;
// First n in the below condition
// is for the case where n is 0
if ($n && !($n&($n - 1)))
return $n;
while($n != 0)
{
$n >>= 1;
$count += 1;
}
return 1 << $count;
}
// Driver Code
$n = 0;
echo (nextPowerOf2($n));
// This code is contributed by vt_m
1823
Chapter 296. Smallest power of 2 greater than or equal to n
?>
Output :
#include<stdio.h>
unsigned int nextPowerOf2(unsigned int n)
{
unsigned int p = 1;
if (n && !(n & (n - 1)))
return n;
while (p < n)
p <<= 1;
return p;
}
// Driver Code
int main()
{
unsigned int n = 5;
printf("%d", nextPowerOf2(n));
return 0;
}
Java
1824
Chapter 296. Smallest power of 2 greater than or equal to n
int p = 1;
if (n > 0 && (n & (n - 1)) == 0)
return n;
while (p < n)
p <<= 1;
return p;
}
// Driver Code
public static void main(String args[])
{
int n = 5;
System.out.println(nextPowerOf2(n));
}
}
// This article is contributed
// by Anshika Goyal.
Python3
def nextPowerOf2(n):
p = 1
if (n and not(n & (n - 1))):
return n
while (p < n) :
p <<= 1
return p;
# Driver Code
n = 5
print(nextPowerOf2(n));
# This code is contributed by
# Smitha Dinesh Semwal
C#
1825
Chapter 296. Smallest power of 2 greater than or equal to n
using System;
class GFG
{
static int nextPowerOf2(int n)
{
int p = 1;
if (n > 0 && (n & (n - 1)) == 0)
return n;
while (p < n)
p <<= 1;
return p;
}
// Driver Code
public static void Main()
{
int n = 5;
Console.Write(nextPowerOf2(n));
}
}
// This code is contributed by Smitha.
PHP
<?php
function nextPowerOf2($n)
{
$p = 1;
if ($n && !($n & ($n - 1)))
return $n;
while ($p < $n)
$p <<= 1;
return $p;
}
// Driver Code
$n = 5;
echo ( nextPowerOf2($n));
// This code is contributed by vt_m.
1826
Chapter 296. Smallest power of 2 greater than or equal to n
?>
Output :
1. Subtract n by 1
n = n -1
Example :
1827
Chapter 296. Smallest power of 2 greater than or equal to n
n = 11111
n = n | n >> 16
n = 11110 | 00000
n = 11111
Program:
#include <stdio.h>
// Finds next power of two
// for n. If n itself is a
// power of two then returns n
unsigned int nextPowerOf2(unsigned int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
// Driver Code
int main()
{
unsigned int n = 5;
printf("%d", nextPowerOf2(n));
return 0;
}
Java
1828
Chapter 296. Smallest power of 2 greater than or equal to n
Python 3
1829
Chapter 296. Smallest power of 2 greater than or equal to n
C#
PHP
<?php
// PHP program to find smallest
// power of 2 greater than or
// equal to n
// Finds next power of
// two for n. If n itself
// is a power of two then
// returns n
1830
Chapter 296. Smallest power of 2 greater than or equal to n
function nextPowerOf2($n)
{
$n--;
$n |= $n >> 1;
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
$n++;
return $n;
}
// Driver Code
$n = 5;
echo nextPowerOf2($n);
// This code contributed by Ajit
?>
Output :
Source
https://www.geeksforgeeks.org/smallest-power-of-2-greater-than-or-equal-to-n/
1831
Chapter 297
Input : 2 10
Output : 2 4 5 6 8 10
Input: 60 95
Output: 60 62 64 65 66 68 70 72 74 75 76 78
80 82 84 85 86 88 90 92 94 95
Approach 1 (Simple):
Hash the indices in an array from a to b and mark each of the indices as 1 or 0.
Space complexity : O(max(a, b))
1832
Chapter 297. Space optimization using bit manipulations
1833
Chapter 297. Space optimization using bit manipulations
Java
Python 3
1834
Chapter 297. Space optimization using bit manipulations
C#
PHP
1835
Chapter 297. Space optimization using bit manipulations
<?php
// PHP program to mark
// numbers as multiple
// of 2 or 5
// Driver Code
$a = 2;
$b = 10;
$size = abs($b - $a) + 1;
$array = array_fill(0, $size, 0);
// Iterate through a to b,
// If it is a multiple of
// 2 or 5 Mark index in
// array as 1
for ($i = $a; $i <= $b; $i++)
if ($i % 2 == 0 || $i % 5 == 0)
$array[$i - $a] = 1;
echo "MULTIPLES of 2 and 5:\n";
for ($i = $a; $i <= $b; $i++)
if ($array[$i - $a] == 1)
echo $i . " ";
// This code is contributed by mits.
?>
Output :
MULTIPLES of 2 and 5:
2 4 5 6 8 10
1836
Chapter 297. Space optimization using bit manipulations
C++
1837
Chapter 297. Space optimization using bit manipulations
// Array is dynamically initialized as
// we are calculating size at run time
int* array = new int[size];
// Iterate through every index from a to b and
// call setbit() if it is a multiple of 2 or 5
for (int i = a; i <= b; i++)
if (i % 2 == 0 || i % 5 == 0)
setbit(array, i - a);
cout << "MULTIPLES of 2 and 5:\n";
for (int i = a; i <= b; i++)
if (checkbit(array, i - a))
cout << i << " ";
return 0;
}
Output:
MULTIPLES of 2 and 5:
2 4 5 6 8 10
Source
https://www.geeksforgeeks.org/space-optimization-using-bit-manipulations/
1838
Chapter 298
• Choose any two adjacent characters in a string s1 and replace one of them by a^b and
the other by a b (a OR b).
Examples:
Approach: Given below is a table which explains all the possibilities of XOR and OR
operations.
X Y X^Y X Y
0 0 0 0
0 1 1 1
1 0 1 1
1 1 0 1
1839
Chapter 298. String transformation using XOR and OR
If the both the string consists of 0’s only and their length is same, conversion is possible,
as two adjacent zero will result in zeros only, irrespective of the operation done on it. If
the both the string have 1’s, follow the steps below to check if String1 can be converted to
String2.
If both of the above conditions are true, it is possible to convert String1 can be converted
to String2.
Below is the implementation of above approach:
C++
1840
Chapter 298. String transformation using XOR and OR
}
// if both string do not have a '1'.
return false;
}
// Driver code
int main()
{
string s1 = "100101";
string s2 = "100000";
if (solve(s1, s2))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
1841
Chapter 298. String transformation using XOR and OR
Python3
1842
Chapter 298. String transformation using XOR and OR
# if lengths are different
if (len(s1) != len(s2)):
return False
l = len(s1)
# iterate to check if
# both strings have 1
for i in range (0, l):
# to check if there is
# even one 1 in string s1
if (s1[i] == '1'):
flag1 = 1;
# to check if there is even
# one 1 in string s2
if (s2[i] == '1'):
flag2 = 1
# if both string
# do not have a '1'.
if (flag1 & flag2):
return True
return False
# Driver code
s1 = "100101"
s2 = "100000"
if solve(s1, s2):
print( "Yes")
else:
print("No")
# This code is contributed
# by Shivi_Aggarwal
C#
// C# program to check if
// string1 can be converted
// to string2 using XOR and
// OR operations
using System;
class GFG
1843
Chapter 298. String transformation using XOR and OR
{
// function to check if
// conversion is possible
// or not
static bool solve(String s1,
String s2)
{
bool flag1 = false,
flag2 = false;
// if lengths are different
if (s1.Length != s2.Length)
return false;
int l = s1.Length;
// iterate to check if
// both strings have 1
for (int i = 0; i < l; i++)
{
// to check if there is
// even one 1 in string s1
if (s1[i] == '1')
flag1 = true;
// to check if there is even
// one 1 in string s2
if (s2[i] == '1')
flag2 = true;
if (flag1 == true &&
flag2 == true)
return true;
}
// if both string do
// not have a '1'.
return false;
}
// Driver code
public static void Main()
{
String s1 = "100101";
String s2 = "100000";
1844
Chapter 298. String transformation using XOR and OR
PHP
<?php
// PHP program to check if string1
// can be converted to string2
// using XOR and OR operations
// function to check if conversion
// is possible or not
function solve($s1, $s2)
{
// if lengths are different
if (strlen($s1) != strlen($s2))
return false;
$l = strlen($s1);
// iterate to check if
// both strings have 1
for ($i = 0; $i < 1; $i++)
{
// to check if there is
// even one 1 in string s1
if ($s1[$i] == '1')
$flag1 = 1;
// to check if there is even
// one 1 in string s2
if ($s2[$i] == '1')
$flag2 = 1;
if ($flag1 && $flag2)
return true;
}
// if both string do
1845
Chapter 298. String transformation using XOR and OR
Output:
Yes
Source
https://www.geeksforgeeks.org/string-transformation-using-xor-and-or/
1846
Chapter 299
The idea is to use bitset container in C++. Using bitset, we can precalculate the existence
all the subset sums in an array in O(n) and answer subsequent queries in just O(1).
We basically use an array of bits bit[] to represent the subset sum of elements in the array.
Size of bit[] should be at least sum of all array elements plus 1 to answer all queries. We keep
of bit[x] as 1 if x is a subset sum of given array, else false. Note that indexing is assumed to
begin with 0.
1847
Chapter 299. Subset sum queries using bitset
Finally, we have the bit array as 1101111011, so, if bit[x] is 1 then a subset sum of x exists
otherwise not. We can clearly observe that a subset sum of all the numbers from 0 to 9
except 2 and 7 exists in the array.
Here is a C++ implementation :
1848
Chapter 299. Subset sum queries using bitset
1849
Chapter 299. Subset sum queries using bitset
// a vector of MAXSUM number of bits
bitset<MAXSUM> bit;
preprocess(bit, arr, n);
processQueries(query, nq, bit);
return 0;
}
Output:
Yes, No,
Time complexity : O(n) for pre-calculating and O(1) for subsequent queries, where n is
the number of elements in the array.
Refer http://stackoverflow.com/questions/12459563/what-is-the-size-of-bitset-in-c for
space requirements of this approach.
Source
https://www.geeksforgeeks.org/subset-sum-queries-using-bitset/
1850
Chapter 300
Examples:
Input: 12
Output: 11
Input: 6
Output: 5
Method 1
To subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit
(we get 0011001111). Finally, flip the rightmost 1 bit also (we get 0011000111) to get the
answer.
C
// C code to subtract
// one from a given number
#include <stdio.h>
int subtractOne(int x)
{
int m = 1;
// Flip all the set bits
1851
Chapter 300. Subtract 1 without arithmetic operators
Java
1852
Chapter 300. Subtract 1 without arithmetic operators
}
}
// This code is contributed
// by anuj_67.
C#
// C# code to subtract
// one from a given number
using System;
class GFG
{
static int subtractOne(int x)
{
int m = 1;
// Flip all the set bits
// until we find a 1
while (!((x & m) > 0))
{
x = x ^ m;
m <<= 1;
}
// flip the rightmost
// 1 bit
x = x ^ m;
return x;
}
// Driver Code
public static void Main ()
{
Console.WriteLine(subtractOne(13));
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP code to subtract
// one from a given number
1853
Chapter 300. Subtract 1 without arithmetic operators
function subtractOne($x)
{
$m = 1;
// Flip all the set bits
// until we find a 1
while (!($x & $m))
{
$x = $x ^ $m;
$m <<= 1;
}
// flip the
// rightmost 1 bit
$x = $x ^ $m;
return $x;
}
// Driver Code
echo subtractOne(13);
// This code is contributed
// by anuj_67.
?>
Output:
12
#include <stdio.h>
1854
Chapter 300. Subtract 1 without arithmetic operators
int subtractOne(int x)
{
return ((x << 1) + (~x));
}
/* Driver program to test above functions*/
int main()
{
printf("%d", subtractOne(13));
return 0;
}
Output:
12
Improved By : vt_m
Source
https://www.geeksforgeeks.org/subtract-1-without-arithmetic-operators/
1855
Chapter 301
X Y Diff Borrow
0 0 0 0
0 1 1 1
1 0 1 0
1 1 0 0
From the above table one can draw the Karnaugh map for “difference” and “borrow”.
So, Logic equations are:
Diff = y � x
Borrow = x' . y
1856
Chapter 301. Subtract two numbers without using arithmetic operators
Java
1857
Chapter 301. Subtract two numbers without using arithmetic operators
// is no carry
while (y != 0)
{
// borrow contains common
// set bits of y and unset
// bits of x
int borrow = (~x) & y;
// Subtraction of bits of x
// and y where at least one
// of the bits is not set
x = x ^ y;
// Borrow is shifted by one
// so that subtracting it from
// x gives the required sum
y = borrow << 1;
}
return x;
}
// Driver Code
public static void main (String[] args)
{
int x = 29, y = 13;
System.out.println("x - y is " +
subtract(x, y));
}
}
// This code is contributed by vt_m
Python3
1858
Chapter 301. Subtract two numbers without using arithmetic operators
C#
1859
Chapter 301. Subtract two numbers without using arithmetic operators
PHP
<?php
// PHP Program to subtract two Number
// without using arithetic operater
function subtract($x, $y)
{
// Iterate till there is no carry
while ($y != 0)
{
// borrow contains common set
// bits of y and unset
// bits of x
$borrow = (~$x) & $y;
// Subtraction of bits of x
// and y where at least
// one of the bits is not set
$x = $x ^ $y;
// Borrow is shifted by one so
// that subtracting it from
// x gives the required sum
$y = $borrow << 1;
1860
Chapter 301. Subtract two numbers without using arithmetic operators
}
return $x;
}
// Driver Code
$x = 29; $y = 13;
echo "x - y is ", subtract($x,$y);
// This code is contributed by Ajit
?>
Output :
x - y is 16
#include<stdio.h>
int subtract(int x, int y)
{
if (y == 0)
return x;
return subtract(x ^ y, (~x & y) << 1);
}
// Driver program
int main()
{
int x = 29, y = 13;
printf("x - y is %d", subtract(x, y));
return 0;
}
Java
1861
Chapter 301. Subtract two numbers without using arithmetic operators
if (y == 0)
return x;
return subtract(x ^ y, (~x & y) << 1);
}
// Driver program
public static void main(String[] args)
{
int x = 29, y = 13;
System.out.printf("x - y is %d",
subtract(x, y));
}
}
// This code is contributed by
// Smitha Dinesh Semwal.
Python3
# Python Program to
# subtract two Number
# without using arithmetic operator
# Recursive implementation.
def subtract(x, y):
if (y == 0):
return x
return subtract(x ^ y, (~x & y) << 1)
# Driver program
x = 29
y = 13
print("x - y is", subtract(x, y))
# This code is contributed by
# Smitha Dinesh Semwal
C#
1862
Chapter 301. Subtract two numbers without using arithmetic operators
static int subtract(int x, int y)
{
if (y == 0)
return x;
return subtract(x ^ y, (~x & y) << 1);
}
// Driver program
public static void Main()
{
int x = 29, y = 13;
Console.WriteLine("x - y is "+
subtract(x, y));
}
}
// This code is contributed by anuj_67.
PHP
<?php
function subtract($x, $y)
{
if ($y == 0)
return $x;
return subtract($x ^ $y,
(~$x & $y) << 1);
}
// Driver Code
$x = 29; $y = 13;
echo "x - y is ", subtract($x, $y);
# This code is contributed by ajit
?>
Output :
x - y is 16
This article is contributed Dheeraj. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : jit_t, vt_m
1863
Chapter 301. Subtract two numbers without using arithmetic operators
Source
https://www.geeksforgeeks.org/subtract-two-numbers-without-using-arithmetic-operators/
1864
Chapter 302
Input : Q = 2
L = 3, R = 7
L = 10, R = 16
Output : 5
6
For the first query, valid numbers are 3, 4, 5, 6, and 7.
For the second query, valid numbers are 10, 11, 12, 13, 14 and 16.
1865
Chapter 302. Sudo Placement | Range Queries
C++
1866
Chapter 302. Sudo Placement | Range Queries
Java
1867
Chapter 302. Sudo Placement | Range Queries
import java.util.*;
import java.io.*;
public class RangeQueries {
//Class to store the L and R range of a query
static class Query {
long L;
long R;
}
//It returns index of first element which is grater than searched value
//If searched element is bigger than any array element function
// returns first index after last element.
public static int upperBound(ArrayList<Long> validNumbers,
Long value)
{
int low = 0;
int high = validNumbers.size()-1;
while(low < high){
int mid = (low + high)/2;
if(value >= validNumbers.get(mid)){
low = mid+1;
} else {
high = mid;
}
}
return low;
}
public static void answerQueries(ArrayList<Query> queries){
// Set of Numbers having at most 3 set bits
// arranged in non-descending order
Set<Long> allNum = new HashSet<>();
//0 Set bits
allNum.add(0L);
//Iterate over all possible combinations of i, j, k for
// 60 bits. And add all the numbers with 0, 1 or 2 set bits into
// the set allNum.
for(int i=0; i<=60; i++){
for(int j=0; j<=60; j++){
for(int k=0; k<=60; k++){
//For one set bit, check if i, j, k are equal
//if yes, then set that bit and add it to the set
1868
Chapter 302. Sudo Placement | Range Queries
1869
Chapter 302. Sudo Placement | Range Queries
R = temp;
}
if(L == 0){
int indxOfLastNum = upperBound(validNumbers, R);
System.out.println(indxOfLastNum+1);
}
else {
int indxOfFirstNum = upperBound(validNumbers, L);
int indxOfLastNum = upperBound(validNumbers, R);
System.out.println((indxOfLastNum - indxOfFirstNum +1));
}
}
}
public static void main(String[] args){
int Q = 2;
ArrayList<Query> queries = new ArrayList<>();
Query q1 = new Query();
q1.L = 3;
q1.R = 7;
Query q2 = new Query();
q2.L = 10;
q2.R = 16;
queries.add(q1);
queries.add(q2);
answerQueries(queries);
}
}
Source
https://www.geeksforgeeks.org/sudo-placement-range-queries/
1870
Chapter 303
A Brute Force approach is to run two loops and time complexity is O(n2 ).
C++
1871
Chapter 303. Sum of Bitwise And of all pairs in a given array
// Returns value of "arr[0] & arr[1] + arr[0] & arr[2] +
// ... arr[i] & arr[j] + ..... arr[n-2] & arr[n-1]"
int pairAndSum(int arr[], int n)
{
int ans = 0; // Initialize result
// Consider all pairs (arr[i], arr[j) such that
// i < j
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
ans += arr[i] & arr[j];
return ans;
}
// Driver program to test above function
int main()
{
int arr[] = {5, 10, 15};
int n = sizeof(arr) / sizeof (arr[0]);
cout << pairAndSum(arr, n) << endl;
return 0;
}
Java
1872
Chapter 303. Sum of Bitwise And of all pairs in a given array
// Driver program to test above function
public static void main(String args[])
{
int arr[] = {5, 10, 15};
int n = arr.length;
System.out.println(pairAndSum(arr, n) );
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3
C#
1873
Chapter 303. Sum of Bitwise And of all pairs in a given array
PHP
<?php
// A Simple PHP program to
// compute sum of bitwise
// AND of all pairs
// Returns value of "arr[0] &
// arr[1] + arr[0] & arr[2] +
// ... arr[i] & arr[j] + .....
// arr[n-2] & arr[n-1]"
function pairAndSum($arr, $n)
{
// Initialize result
$ans = 0;
// Consider all pairs (arr[i],
// arr[j) such that i < j
for ($i = 0; $i < $n; $i++)
for ( $j = $i + 1; $j < $n; $j++)
1874
Chapter 303. Sum of Bitwise And of all pairs in a given array
Output :
15
An Efficient Solution can solve this problem in O(n) time. The assumption here is that
integers are represented using 32 bits.
The idea is to count number of set bits at every i’th position (i>=0 && i<=31). Any i’th
bit of the AND of two numbers is 1 iff the corresponding bit in both the numbers is equal
to 1.
Let k be the count of set bits at i’th position. Total number of pairs with i’th set bit would
be k C2 = k*(k-1)/2 (Count k means there are k numbers which have i’th set bit). Every
such pair adds 2i to total sum. Similarly, we work for all other places and add the sum to
our final answer.
This idea is similar to this. Below is the implementation.
C
1875
Chapter 303. Sum of Bitwise And of all pairs in a given array
Java
1876
Chapter 303. Sum of Bitwise And of all pairs in a given array
// There are k set bits, means k(k-1)/2 pairs.
// Every pair adds 2^i to the answer. Therefore,
// we add "2^i * [k*(k-1)/2]" to the answer.
ans += (1 << i) * (k * (k - 1)/2);
}
return ans;
}
// Driver program to test above function
public static void main(String args[])
{
int arr[] = {5, 10, 15};
int n = arr.length;
System.out.println(pairAndSum(arr, n));
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3
1877
Chapter 303. Sum of Bitwise And of all pairs in a given array
C#
1878
Chapter 303. Sum of Bitwise And of all pairs in a given array
PHP
<?php
// An efficient PHP program to
// compute sum of bitwise AND
// of all pairs
// Returns value of "arr[0] &
// arr[1] + arr[0] & arr[2] +
// ... arr[i] & arr[j] + .....
// arr[n-2] & arr[n-1]"
function pairAndSum($arr, $n)
{
// Initialize result
$ans = 0;
// Traverse over all bits
for ($i = 0; $i < 32; $i++)
{
// Count number of elements
// with i'th bit set
// Initialize the count
$k = 0;
for ($j = 0; $j < $n; $j++)
if (($arr[$j] & (1 << $i)) )
$k++;
// There are k set bits,
// means k(k-1)/2 pairs.
// Every pair adds 2^i to
// the answer. Therefore,
// we add "2^i * [k*(k-1)/2]"
// to the answer.
$ans += (1 << $i) * ($k * ($k - 1) / 2);
}
return $ans;
}
1879
Chapter 303. Sum of Bitwise And of all pairs in a given array
// Driver Code
$arr = array(5, 10, 15);
$n = sizeof($arr);
echo pairAndSum($arr, $n) ;
// This code is contributed by nitin mittal.
?>
Output:
15
This article is contributed by Ekta Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Nikita tiwari, nitin mittal, Smitha Dinesh Semwal, jit_t
Source
https://www.geeksforgeeks.org/calculate-sum-of-bitwise-and-of-all-pairs/
1880
Chapter 304
Naive Solution
A Brute Force approach is to run two loops and time complexity is O(n2 ).
C++
1881
Chapter 304. Sum of XOR of all pairs in an array
Java
1882
Chapter 304. Sum of XOR of all pairs in an array
Python3
1883
Chapter 304. Sum of XOR of all pairs in an array
# This code is contributed by Nikita Tiwari.
C#
PHP
<?php
// A Simple PHP program to compute
// sum of bitwise OR of all pairs
1884
Chapter 304. Sum of XOR of all pairs in an array
// Returns sum of bitwise OR
// of all pairs
function pairORSum($arr, $n)
{
// Initialize result
$ans = 0;
// Consider all pairs
// (arr[i], arr[j) such that
// i < j
for ( $i = 0; $i < $n; $i++)
for ( $j = $i + 1; $j < $n; $j++)
$ans += $arr[$i] ^ $arr[$j];
return $ans;
}
// Driver Code
$arr = array( 5, 9, 7, 6 );
$n = count($arr);
echo pairORSum($arr, $n) ;
// This code is contributed by anuj_67.
?>
Output :
47
Efficient Solution
An Efficient Solution can solve this problem in O(n) time. The assumption here is that
integers are represented using 32 bits.
Optimized solution will be to try bit manipulation. To implement the solution, we consider
all bits which are 1 and which are 0 and store their count in two different variables. Next
multiple those counts along with the power of 2 raised to that bit position. Do this for all
the bit positions of the numbers. Their sum would be our answer.
Explanation : arr[] = { 7, 3, 5 }
7 = 1 1 1
3 = 0 1 1
5 = 1 0 1
For bit position 0 :
Bits with zero = 0
Bits with one = 3
Answer = 0 * 3 * 2 ^ 0 = 0
1885
Chapter 304. Sum of XOR of all pairs in an array
CPP
1886
Chapter 304. Sum of XOR of all pairs in an array
Java
1887
Chapter 304. Sum of XOR of all pairs in an array
Python3
1888
Chapter 304. Sum of XOR of all pairs in an array
# calculating individual bit sum
idsum = oc * zc * (1 << i)
# final sum
sum = sum + idsum;
return sum
# driver function
sum = 0
arr = [ 5, 9, 7, 6 ]
n = len(arr)
sum = sumXOR(arr, n);
print (sum)
# This code is contributed by saloni1297
C#
1889
Chapter 304. Sum of XOR of all pairs in an array
arr[j] /= 2;
}
// calculating individual bit sum
idsum = oc * zc * (1 << i);
// final sum
sum += idsum;
}
return sum;
}
// Driver Code
public static void Main()
{
long sum = 0;
int []arr = { 5, 9, 7, 6 };
int n = arr.Length;
sum = sumXOR(arr, n);
Console.WriteLine(sum);
}
}
// This code is contributed by vt_m.
PHP
<?php
// An efficient PHP program to compute
// sum of bitwise OR of all pairs
// Returns sum of bitwise OR
// of all pairs
function sumXOR($arr, $n)
{
$sum = 0;
for ($i = 0; $i < 32; $i++)
{
// Count of zeros and ones
$zc = 0; $oc = 0;
// Individual sum at each
// bit position
$idsum = 0;
for ($j = 0; $j < $n; $j++)
{
if ($arr[$j] % 2 == 0)
1890
Chapter 304. Sum of XOR of all pairs in an array
$zc++;
else
$oc++;
$arr[$j] /= 2;
}
// calculating individual bit sum
$idsum = $oc * $zc * (1 << $i);
// final sum
$sum += $idsum;
}
return $sum;
}
// Driver code
$sum = 0;
$arr = array( 5, 9, 7, 6 );
$n = count($arr);
$sum = sumXOR($arr, $n);
echo $sum;
// This code is contributed by anuj_67
?>
Output:
47
Improved By : vt_m
Source
https://www.geeksforgeeks.org/sum-xor-pairs-array/
1891
Chapter 305
A naive approach is to consider all the pairs one by one, calculate their XOR one after
the other.
C++
1892
Chapter 305. Sum of XOR of sum of all pairs in an array
Java
Python3
1893
Chapter 305. Sum of XOR of sum of all pairs in an array
def xor_pair_sum(ar, n):
total = 0
for i in range(n):
for j in range(n):
total = total ^ (ar[i] + ar[j])
return total
# Driver program to test the above function
if __name__ == "__main__":
data = [1, 2, 3]
print(xor_pair_sum(data, len(data)))
# This code is contributed
# by Kanav Malhotra
C#
// C# program to find
// XOR of pair sums.
using System;
class GFG
{
static int xorPairSum(int []ar,
int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum = sum ^ (ar[i] + ar[j]);
return sum;
}
// Driver code
static public void Main(String []args)
{
int []arr = { 1, 2, 3 };
int n = arr.Length;
Console.WriteLine(xorPairSum(arr, n));
}
}
// This code is contributed
// by Arnab Kundu
1894
Chapter 305. Sum of XOR of sum of all pairs in an array
PHP
<?php
// PHP program to find
// XOR of pair sums.
function xorPairSum($ar, $n)
{
$sum = 0;
for ($i = 0; $i < $n; $i++)
$sum = $sum ^ ($ar[$i] +
$ar[$j]);
return $sum;
}
// Driver code
$arr = array( 1, 2, 3 );
$n = count($arr);
echo xorPairSum($arr, $n);
// This code is contributed
// by Subhadeep
?>
Output:
C++
1895
Chapter 305. Sum of XOR of sum of all pairs in an array
return 2*sum;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << xorPairSum(arr, n);
return 0;
}
Java
Python3
1896
Chapter 305. Sum of XOR of sum of all pairs in an array
for i in range(n):
total = total ^ ar[i]
return 2 * total
# Driver program to test the above function
if __name__ == "__main__":
data = [1, 2, 3]
print(xor_pair_sum(data, len(data)))
# This code is contributed
# by Kanav Malhotra
C#
// C# program to find
// XOR of pair sums.
using System;
class GFG
{
static int xorPairSum(int []ar,
int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum = sum ^ ar[i];
return 2 * sum;
}
// Driver code
static public void Main(String []args)
{
int []arr = { 1, 2, 3 };
int n = arr.Length;
Console.WriteLine( xorPairSum(arr, n));
}
}
// This code is contributed
// by Arnab Kundu
PHP
<?php
1897
Chapter 305. Sum of XOR of sum of all pairs in an array
Output:
Source
https://www.geeksforgeeks.org/sum-of-xor-of-sum-of-all-pairs-in-an-array/
1898
Chapter 306
Input : 2
Output : 7
Explanation: row 0 have element 1
row 1 have elements 1, 1
row 2 have elements 1, 2, 1
so, sum will be ((1) + (1 + 1) + (1 + 2 + 1)) = 7
Input : 4
Output : 31
Explanation: row 0 have element 1
row 1 have elements 1, 1
row 2 have elements 1, 2, 1
row 3 have elements 1, 3, 3, 1
row 4 have elements 1, 4, 6, 4, 1
so, sum will be ((1) + (1 + 1) + (1 + 2 + 1)
+ (1 + 3 + 3 + 1) + (1 + 4 + 6 + 4 + 1)) = 31
Pascal's triangle
1899
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
0th row 1
1st row 1 1
2nd row 1 2 1
3rd row 1 13 3
4th row 1 6 44 1
5th row 1 5 10 10 5 1
6th row 1 6 15 20 15 6 1
7th row 1 7 21 35 35 21 7 1
8th row 1 8 28 56 70 56 28 8 1
9th row 1 9 36 84 126 126 84 36 9 1
10th row 1 10 45 120 210 256 210 120 45 10 1
Naive Approach: In a Pascal triangle, each entry of a row is value of binomial coefficient.
So a simple solution is to generating all row elements up to nth row and adding them. But
this approach will have O(n3 ) time complexity. However, it can be optimized up to O(n2 )
time complexity. Refer the following article to generate elements of Pascal’s triangle:
• Pascal’s triangle
As shown above, the sum of elements in the ith row is equal to 2i . Now it can be easily
calculated the sum of all elements up to nth row by adding powers of 2.
Below is the implementation of above approach:
C++
1900
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
Java
1901
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
return sum;
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println("Sum of all elements:"
+ calculateSum(n));
}
}
Python3
C#
1902
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
{
// Initialize sum with 0
long sum = 0;
// Loop to calculate power of 2
// upto n and add them
for (int row = 0; row < n; row++) {
sum = sum + (1 << row);
}
return sum;
}
static public void Main()
{
int n = 10;
Console.WriteLine("Sum of all elements:"
+ calculateSum(n));
}
}
PHP
<?php
// PHP program to find sum of
// all elements upto nth row
// in Pascal triangle.
// Function to find sum of
// all elements upto nth row.
function calculateSum($n)
{
// Initialize sum with 0
$sum = 0;
// Loop to calculate power
// of 2 upto n and add them
for ($row = 0; $row < $n; $row++)
{
$sum = $sum + (1 << $row);
}
return $sum;
}
// Driver Code
1903
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
$n = 10;
echo " Sum of all elements : " .
calculateSum($n);
// This code is contributed by Mahadev.
?>
Output:
2n can be expressed as
2n = ( 20 + 21 + 22 + 23 +. . . + 2(n-1) ) + 1
For Example:
26 = ( 20 + 21 + 22 + 23 + 24 + 25 ) + 1
64 = ( 1 + 2 + 4 + 8 +16 + 32 ) + 1
64 = 63 + 1
So, calculate 2n instead of calculating every power of 2 up to (n – 1) and from above example
the sum of the power of 2 up to (n – 1) will be (2n – 1).
C++
1904
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
// Driver function
int main()
{
int n = 10;
cout << " Sum of all elements:" << calculateSum(n);
return 0;
}
Java
Python3
1905
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
def calculateSum(n) :
# Initialize sum with 0
sum = 0
# Calculate 2 ^ n
sum = 1 << n;
return (sum - 1)
# Driver unicode
n = 10
print("Sum of all elements:", calculateSum(n))
C#
PHP
<?php
1906
Chapter 306. Sum of all elements up to Nth row in a Pascal triangle
Output:
Source
https://www.geeksforgeeks.org/sum-of-all-elements-up-to-nth-row-in-a-pascals-triangle/
1907
Chapter 307
1908
Chapter 307. Sum of bit differences among all pairs
A Simple Solution is to run two loops to consider all pairs one by one. For every pair,
count bit differences. Finally return sum of counts. Time complexity of this solution is
O(n2 ).
An Efficient Solution can solve this problem in O(n) time using the fact that all numbers
are represented using 32 bits (or some fixed number of bits). The idea is to count differences
at individual bit positions. We traverse from 0 to 31 and count numbers with i’th bit set.
Let this count be ‘count’. There would be “n-count” numbers with i’th bit not set. So count
of differences at i’th bit would be “count * (n-count) * 2”.
Below is implementation of above idea.
C++
Java
1909
Chapter 307. Sum of bit differences among all pairs
Python3
1910
Chapter 307. Sum of bit differences among all pairs
def sumBitDifferences(arr,n):
ans = 0 # Initialize result
# traverse over all bits
for i in range(0, 32):
# count number of elements with i'th bit set
count = 0
for j in range(0,n):
if ( (arr[j] & (1 << i)) ):
count+=1
# Add "count * (n - count) * 2" to the answer
ans += (count * (n - count) * 2);
return ans
# Driver prorgram
arr = [1, 3, 5]
n = len(arr )
print(sumBitDifferences(arr, n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
1911
Chapter 307. Sum of bit differences among all pairs
PHP
<?php
// PHP program to compute sum
// of pairwise bit differences
function sumBitDifferences($arr, $n)
{
// Initialize result
$ans = 0;
// traverse over all bits
for ($i = 0; $i < 32; $i++)
{
// count number of elements
// with i'th bit set
$count = 0;
for ($j = 0; $j < $n; $j++)
if (($arr[$j] & (1 << $i)))
$count++;
// Add "count * (n - count) * 2"
// to the answer
$ans += ($count * ($n -
$count) * 2);
1912
Chapter 307. Sum of bit differences among all pairs
}
return $ans;
}
// Driver Code
$arr = array(1, 3, 5);
$n = sizeof($arr);
echo sumBitDifferences($arr, $n), "\n";
// This code is contributed by m_kit
?>
Output :
Source
https://www.geeksforgeeks.org/sum-of-bit-differences-among-all-pairs/
1913
Chapter 308
Input : 1 2 3
Output : 9
For [1, 2, 3], all possible subsets are {1},
{2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}
Bitwise AND of these subsets are, 1 + 2 +
3 + 0 + 1 + 2 + 0 = 9.
So, the answer would be 9.
Input : 1 2 3 4
Output : 13
1914
Chapter 308. Sum of bitwise AND of all possible subsets of given set
Array = {1, 2, 3}
Binary representation
positions 2 1 0
1 0 0 1
2 0 1 0
3 0 1 1
[ 0 2 2 ]
Count set bit for each position
[ 0 3 3 ] subset produced by each
position 2^n -1 i.e. n is total sum
for each position [ 0, 3*2^1, 3*2^0 ]
Now calculate the sum by multiplying
the position value i.e 2^0, 2^1 ... .
0 + 6 + 3 = 9
CPP
1915
Chapter 308. Sum of bitwise AND of all possible subsets of given set
Java
1916
Chapter 308. Sum of bitwise AND of all possible subsets of given set
Python3
1917
Chapter 308. Sum of bitwise AND of all possible subsets of given set
C#
1918
Chapter 308. Sum of bitwise AND of all possible subsets of given set
PHP
<?php
// PHP program to calculate sum of Bit-wise
// and sum of all subsets of an array
$BITS = 32;
function andSum( $arr, $n)
{
global $BITS;
$ans = 0;
1919
Chapter 308. Sum of bitwise AND of all possible subsets of given set
Output:
1920
Chapter 308. Sum of bitwise AND of all possible subsets of given set
Source
https://www.geeksforgeeks.org/sum-bitwise-possible-subsets-given-set/
1921
Chapter 309
A Naive approach is to take the OR all possible combination of array[] elements and
1922
Chapter 309. Sum of bitwise OR of all possible subsets of given set
then perform the summation of all values. Time complexity of this approach grows
exponentially so it would not be better for large value of n.
An Efficient approach is to find the pattern with respect to the property of OR. Now again
consider the subset in binary form like:
1 = 001
2 = 010
3 = 011
1 | 2 = 011
1 | 3 = 011
2 | 3 = 011
1|2|3 = 011
Insted of taking the OR of all possible elements of array, Here we will consider all possible
subset with ith bit 1.
Now, consider the ith bit in all the resultant ORs, it is zero only if all the ith bit of elements
in the subset is 0.
Number of subset with ith bit 1 = total possible subsets – subsets with all ith bit 0. Here,
total subsets = 2^n – 1 and subsets with all ith bits 0 = 2^( count of zeros at ith bit of
all the elements of array) – 1. Now, Total subset OR with ith bit 1 = (2^n-1)-(2^(count of
zeros at ith bit)-1). Total value contributed by those bits with value 1 = total subset OR
with ith bit 1 *(2^i).
Now, total sum = (total subset with ith bit 1) * 2^i + (total subset with i+1th bit 1) *
2^(i+1) + ……… + (total subset with 32 bit 1) * 2^32.
C++
1923
Chapter 309. Sum of bitwise OR of all possible subsets of given set
Java
1924
Chapter 309. Sum of bitwise OR of all possible subsets of given set
zerocnt[i] += 1;
// for each index the OR
// sum contributed by that
// bit of subset will be
// 2^(bit index) now the OR
// of the bits is 0 only if
// all the ith bit of the
// elements in subset is 0.
int ans = 0;
for (int i = 0; i < INT_SIZE; i++)
{
ans += ((Math.pow(2, n) - 1) -
(Math.pow(2, zerocnt[i]) - 1)) *
Math.pow(2, i);
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3 };
int size = arr.length;
System.out.println(ORsum(arr, size));
}
}
// This code is contributed by Sam007
Python3
INT_SIZE = 32
# function to find the OR_SUM
def ORsum(arr, n):
# create an array of size 32
# and store the sum of bits
# with value 0 at every index.
zerocnt = [0 for i in range(INT_SIZE)]
for i in range(INT_SIZE):
for j in range(n):
if not (arr[j] & (1 << i)):
zerocnt[i] += 1
1925
Chapter 309. Sum of bitwise OR of all possible subsets of given set
C#
// C# code to find
// the OR_SUM
using System;
class GFG {
static int INT_SIZE = 32;
// function to find
// the OR_SUM
static int ORsum(int []arr, int n)
{
// create an array of size 32
// and store the sum of bits
// with value 0 at every index.
int []zerocnt = new int[INT_SIZE] ;
for (int i = 0; i < INT_SIZE; i++)
for (int j = 0; j < n; j++)
if ((arr[j] & 1 << i) == 0)
zerocnt[i] += 1;
// for each index the OR
// sum contributed by that
// bit of subset will be
1926
Chapter 309. Sum of bitwise OR of all possible subsets of given set
Output:
18
Source
https://www.geeksforgeeks.org/sum-of-bitwise-or-of-all-possible-subsets-of-given-set/
1927
Chapter 310
Input : 1 2 3 4 5
Output : 71
Input : 6 5 4 3 2
Output : 84
1928
Chapter 310. Sum of bitwise OR of all subarrays
First initialize the two variable sum=0, sum1=0, variable sum will store the total sum and,
with sum1 we will perform bitwise OR operation for each jth element, and add sum1 with
sum.
1:- Traverse the from 0th position to n-1.
2:- For each ith variable we will perform bit wise OR operation on all the sub arrays to find
the total sum.
Repeat step until the whole array is traverse.
C++
1929
Chapter 310. Sum of bitwise OR of all subarrays
1930
Chapter 310. Sum of bitwise OR of all subarrays
// perform Bitwise OR operation
// on all the subarray present in array
for (j = i; j < n; j++) {
// OR operation
sum1 = (sum1 | a[j]);
// now add the sum after performing the
// Bitwise OR operation
sum = sum + sum1;
}
}
return sum;
}
// Driver code
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof(a)/sizeof(a[0]);
printf("%d ", totalSum(a, n));
return 0;
}
Java
1931
Chapter 310. Sum of bitwise OR of all subarrays
{
// OR operation
sum1 = (sum1 | a[j]);
// now add the sum after
// performing the Bitwise
// OR operation
sum = sum + sum1;
}
}
return sum;
}
// Driver code
public static void main(String args[])
{
int a[] = { 1, 2, 3, 4, 5 };
int n = a.length;
System.out.println(totalSum(a,n));
}
}
// This code is contributed
// by Subhadeep
Python3
# Python3 program to find sum of
# bitwise ors of all subarrays.
def totalSum(a, n):
sum = 0;
for i in range(n):
sum1 = 0;
# perform Bitwise OR operation
# on all the subarray present
# in array
for j in range(i, n):
# OR operation
sum1 = (sum1 | a[j]);
# now add the sum after
# performing the
# Bitwise OR operation
sum = sum + sum1;
return sum;
1932
Chapter 310. Sum of bitwise OR of all subarrays
# Driver code
a = [1, 2, 3, 4, 5];
n = len(a);
print(totalSum(a, n));
# This code is contributed by mits
C#
1933
Chapter 310. Sum of bitwise OR of all subarrays
}
// This code is contributed
// by mits
PHP
<?php
// PHP program to find
// sum of bitwise ors
// of all subarrays.
function totalSum($a,$n)
{
$sum = 0;
for ($i = 0; $i < $n; $i++)
{
$sum1 = 0;
// perform Bitwise OR operation
// on all the subarray present
// in array
for ($j = $i; $j < $n; $j++)
{
// OR operation
$sum1 = ($sum1 | $a[$j]);
// now add the sum after
// performing the
// Bitwise OR operation
$sum = $sum + $sum1;
}
}
return $sum;
}
// Driver code
$a = array(1, 2, 3, 4, 5);
$n = sizeof($a);
echo totalSum($a, $n);
// This code is contributed by mits
?>
Output:
71
1934
Chapter 310. Sum of bitwise OR of all subarrays
Source
https://www.geeksforgeeks.org/sum-of-bitwise-or-of-all-subarrays/
1935
Chapter 311
Input : 10
Output : 33
3 + 5 + 6 + 9 + 10 = 33
Input : 100
Output : 762
Naive Approach: Find each number upto n whose 2 bits are set. If its 2 bits are set add
it to the sum.
C++
1936
Chapter 311. Sum of numbers with exactly 2 bits set
count++;
}
return count;
}
// To calculate sum of numbers
int findSum(int n)
{
int sum = 0;
// To count sum of number
// whose 2 bit are set
for (int i = 1; i <= n; i++)
if (countSetBits(i) == 2)
sum += i;
return sum;
}
// Driver program to test above function
int main()
{
int n = 10;
cout << findSum(n);
return 0;
}
Java
1937
Chapter 311. Sum of numbers with exactly 2 bits set
// To count sum of number
// whose 2 bit are set
for (int i = 1; i <= n; i++)
if (countSetBits(i) == 2)
sum += i;
return sum;
}
// Driver program to test above function
public static void main(String[] args)
{
int n = 10;
System.out.println(findSum(n));
}
}
Python3
1938
Chapter 311. Sum of numbers with exactly 2 bits set
# Driver code
n = 10
print(findSum(n))
# This code is contributed
# by Anant Agarwal.
C#
1939
Chapter 311. Sum of numbers with exactly 2 bits set
int n = 10;
Console.WriteLine(findSum(n));
}
}
// This code is contributed by aj_36
PHP
<?php
// PHP program to find sum of numbers
// upto n whose 2 bits are set
// To count number of set bits
function countSetBits($n)
{
$count = 0;
while ($n)
{
$n &= ($n - 1);
$count++;
}
return $count;
}
// To calculate sum of numbers
function findSum($n)
{
$sum = 0;
// To count sum of number
// whose 2 bit are set
for ($i = 1; $i <= $n; $i++)
if (countSetBits($i) == 2)
$sum += $i;
return $sum;
}
// Driver Code
$n = 10;
echo findSum($n);
// This code is contributed by anuj_67.
?>
Output:
1940
Chapter 311. Sum of numbers with exactly 2 bits set
33
Efficient Approach: The number whose 2 bits are set is of the form 2^x + 2^y and this
number is less then n. So we have to find only numbers in the range upto n which is of form
2^i + 2^j where i > 0 and 2^i < n and 0 <= j < i.
C++
Java
1941
Chapter 311. Sum of numbers with exactly 2 bits set
C#
1942
Chapter 311. Sum of numbers with exactly 2 bits set
PHP
<?php
<?php
// PHP program to find sum of numbers
// upto n whose 2 bits are set
// To calculate sum of numbers
function findSum($n)
{
$sum = 0;
// Find numbers whose 2 bits are set
for ($i = 1; (1 << $i) < $n; $i++)
{
for ($j = 0; $j < $i; $j++)
{
$num = (1 << $i) + (1 << $j);
// If number is greater then n
// we don't include this in sum
if ($num <= $n)
$sum += $num;
1943
Chapter 311. Sum of numbers with exactly 2 bits set
}
}
// Return sum of numbers
return $sum;
}
// Driver Code
$n = 10;
echo findSum($n);
// This code is contributed by Ajit
?>
Output :
33
Source
https://www.geeksforgeeks.org/sum-numbers-exactly-2-bits-set/
1944
Chapter 312
Input: 5
Output: 63
20 + 21 + 22 + 23 + 24
= 1 + 2+ 4 + 8 + 16
= 31
Input: 10
Output: 1023
20 + 21 + 2 2 + 23 + 2 3 + 2 4 + 25 + 26 + 27 + 2 8
+ 29
= 1 + 2+ 4 + 8 + 16 + 32 +64 + 128 + 256 + 512
= 1023
1945
Chapter 312. Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n
Java
1946
Chapter 312. Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n
}
};
Python3
C#
1947
Chapter 312. Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n
}
return sum;
}
// Driver code
public static void Main()
{
int n = 10;
Console.WriteLine("Sum of the series : " +
calculateSum(n));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
<?php
// PHP program to find sum of the
// series 2^0 + 2^1 + 2^2 +…..+ 2^n
// function to calculate
// sum of series
function calculateSum($n)
{
// initialize sum as 0
$sum = 0;
// loop to calculate
// sum of series
for ($i = 0; $i < $n; $i++)
{
// calculate 2^i
// and add it to sum
$sum = $sum + (1 << $i);
}
return $sum;
}
// Driver code
$n = 10;
echo "Sum of the series of " .
"power 2 is : ",
calculateSum($n);
1948
Chapter 312. Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n
Output:
Java
1949
Chapter 312. Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n
// calculate 2^(n+1)
int sum = (1 << (n + 1));
return sum - 1;
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println("Sum of the series of power 2 is : "
+ calculateSum(n));
}
};
Python3
C#
// C# program to calculate
// sum of series of power of 2
using System;
class GFG
{
// function to calculate
// sum of series
static int calculateSum(int n)
{
// calculate 2^(n+1)
int sum = (1 << (n + 1));
1950
Chapter 312. Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n
return sum - 1;
}
// Driver code
public static void Main()
{
int n = 10;
Console.Write("Sum of the series " +
"of power 2 is : " +
calculateSum(n));
}
// This code is contributed
// by Smitha
}
PHP
<?php
// PHP program to calculate
// sum of series of power of 2
// function to calculate
// sum of series
function calculateSum($n)
{
// calculate 2^(n+1)
$sum = (1 << ($n + 1));
return $sum - 1;
}
// Driver code
$n = 10;
echo "Sum of the series of " .
"power 2 is : ",
calculateSum($n);
// This code is contributed
// by Smitha
Output:
1951
Chapter 312. Sum of the series 2^0 + 2^1 + 2^2 +…..+ 2^n
Source
https://www.geeksforgeeks.org/sum-of-the-series-20-21-22-2n/
1952
Chapter 313
1953
Chapter 313. Swap all odd and even bits
// Get all odd bits of x
unsigned int odd_bits = x & 0x55555555;
even_bits >>= 1; // Right shift even bits
odd_bits <<= 1; // Left shift odd bits
return (even_bits | odd_bits); // Combine even and odd bits
}
// Driver program to test above function
int main()
{
unsigned int x = 23; // 00010111
// Output is 43 (00101011)
printf("%u ", swapBits(x));
return 0;
}
Java
1954
Chapter 313. Swap all odd and even bits
Python 3
1955
Chapter 313. Swap all odd and even bits
C#
PHP
<?php
// PHP program to swap even and
// odd bits of a given number
1956
Chapter 313. Swap all odd and even bits
Output:
43
Improved By : jit_t
Source
https://www.geeksforgeeks.org/swap-all-odd-and-even-bits/
1957
Chapter 314
1958
Chapter 314. Swap bits in a given number
Implementation:
1959
Chapter 314. Swap bits in a given number
{
int res = swapBits(28, 0, 3, 2);
printf("\nResult = %d ", res);
return 0;
}
Java
Python3
1960
Chapter 314. Swap bits in a given number
# Python program to
# swap bits in a given number
def swapBits(x,p1,p2,n):
# Move all bits of first
# set to rightmost side
set1 = (x >> p1) & ((1<< n) - 1)
# Moce all bits of second
# set to rightmost side
set2 = (x >> p2) & ((1 << n) - 1)
# XOR the two sets
xor = (set1 ^ set2)
# Put the xor bits back
# to their original positions
xor = (xor << p1) | (xor << p2)
# XOR the 'xor' with the
# original number so that the
# two sets are swapped
result = x ^ xor
return result
# Driver code
res =swapBits(28, 0, 3, 2)
print("Result =",res)
# This code is contributed
# by Anant Agarwal.
C#
1961
Chapter 314. Swap bits in a given number
// Move all bits of second set
// set to rightmost side
int set2 = (x >> p2) & ((1 << n) - 1);
// XOR the two sets
int xor = (set1 ^ set2);
// Put the xor bits back to
// their original positions
xor = (xor << p1) | (xor << p2);
// XOR the 'xor' with the original number
// so that the two sets are swapped
int result = x ^ xor;
return result;
}
// Driver program
public static void Main()
{
int res = swapBits(28, 0, 3, 2);
Console.WriteLine("Result = " + res);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to swap bits
// in a given number
// function returns
// the swapped bits
function swapBits($x, $p1, $p2, $n)
{
// Move all bits of first
// set to rightmost side
$set1 = ($x >> $p1) &
((1 << $n) - 1);
// Move all bits of second
// set to rightmost side
$set2 = ($x >> $p2) &
1962
Chapter 314. Swap bits in a given number
Output:
Result = 7
int swapBits(unsigned int x, unsigned int p1, unsigned int p2, unsigned int n)
{
/* xor contains xor of two sets */
unsigned int xor = ((x >> p1) ^ (x >> p2)) & ((1U << n) - 1);
/* To swap two sets, we need to again XOR the xor with original sets */
return x ^ ((xor << p1) | (xor << p2));
}
References:
Swapping individual bits with XOR
Improved By : vt_m
Source
https://www.geeksforgeeks.org/swap-bits-in-a-given-number/
1963
Chapter 315
Input : 00000010
Output : 00000001
Input : 00000100
Output : 00001000
Approach:
x = ((x & 0b10101010) >> 1) | ((x & 0b01010101) <> 1 extracts the high bit position and
shifts it to the low bit position.
Similarly the expression (x & 0b01010101) << 1 extracts the low bit from each pair and
shifts it to the high bit position.
The two parts are then combined using bitwise-OR.
x= 00011010
((x & 0b10101010) >> 1) = 00001010 >> 1
= 00000101
((x & 0b01010101) << 1) = 00010000 <> 1) | ((x & 0b01010101) << 1) = 00100101
C++
1964
Chapter 315. Swap every two bits in bytes
Java
Python3
1965
Chapter 315. Swap every two bits in bytes
C#
PHP
<?php
// PHP program to swap every
1966
Chapter 315. Swap every two bits in bytes
Output:
Reference:
https://stackoverflow.com/questions/4788799/swap-every-pair-of-bits-in-byte
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/swap-every-two-bits-bytes/
1967
Chapter 316
1968
Chapter 316. Swap three variables without using temporary variable
C#
1969
Chapter 316. Swap three variables without using temporary variable
PHP
<?php
// PHP program to swap three
// variables without using
// temporary variable.
// Assign c's value to a,
// a's value to b and
// b's value to c.
function swapThree(&$a, &$b, &$c)
{
// Store sum of all in a
$a = $a + $b + $c; // (a = 60)
// After this, b has value of a
// (b = 60 – (20+30) =10)
$b = $a - ($b + $c);
1970
Chapter 316. Swap three variables without using temporary variable
Output :
1971
Chapter 316. Swap three variables without using temporary variable
C#
1972
Chapter 316. Swap three variables without using temporary variable
// After this, b has value of a
b = a ^ b ^ c;
// After this, c has value of b
c = a ^ b ^ c;
// After this, a has value of c
a = a ^ b ^ c;
}
// Driver Code
static void Main(String []args)
{
int a = 10, b = 20, c = 30;
Console.WriteLine( "Before swapping a = " +
a +", b = " + b +
",c = " + c);
// Calling Function
swapThree(ref a, ref b,ref c);
Console.Write("After swapping a = " +
a +", b = " + b +
", c = " + c);
}
}
// This code is contributed by Sam007.
PHP
<?php
//PHP program to swap three variables
// without using temporary variable
// Assign c's value to a, a's value to b and
// b's value to c.
function swapThree(&$a, &$b, &$c)
{
// Store XOR of all in a
$a = $a ^ $b ^ $c;
1973
Chapter 316. Swap three variables without using temporary variable
Output:
The method 1 causes overflow for large values of a, b and c, while method 2 doesn’t.
Improved By : Sam007, jit_t
Source
https://www.geeksforgeeks.org/swap-three-variables-without-using-temporary-variable/
1974
Chapter 317
#include <stdio.h>
unsigned char swapNibbles(unsigned char x)
{
return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}
int main()
{
unsigned char x = 100;
printf("%u", swapNibbles(x));
return 0;
}
Java
1975
Chapter 317. Swap two nibbles in a byte
class GFG {
static int swapNibbles(int x)
{
return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);
}
// Driver code
public static void main(String arg[])
{
int x = 100;
System.out.print(swapNibbles(x));
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
1976
Chapter 317. Swap two nibbles in a byte
// Driver code
public static void Main()
{
int x = 100;
Console.Write(swapNibbles(x));
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to swap two
// nibbles in a byte
// function to Swap two nibbles
// in a byte in php program
function swapNibbles($x)
{
return ( ($x & 0x0F) << 4 |
($x & 0xF0) >> 4 );
}
// Driver Code
$x = 100;
echo swapNibbles($x);
// This Code is Contributed by Ajit
?>
Output:
70
Explanation:
100 is 01100100 in binary. The operation can be split mainly in two parts
1) The expression “x & 0x0F” gives us last 4 bits of x. For x = 100, the result is 00000100.
Using bitwise ‘<<’ operator, we shift the last four bits to the left 4 times and make the new
last four bits as 0. The result after shift is 01000000.
2) The expression “x & 0xF0” gives us first four bits of x. For x = 100, the result is
01100000. Using bitwise ‘>>’ operator, we shift the digit to the right 4 times and make the
first four bits as 0. The result after shift is 00000110.
At the end we use the bitwise OR ‘|’ operation of the two expressions explained above. The
OR operator places first nibble to the end and last nibble to first. For x = 100, the value of
(01000000) OR (00000110) gives the result 01000110 which is equal to 70 in decimal.
1977
Chapter 317. Swap two nibbles in a byte
This article is contributed by Anuj Garg. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, jit_t
Source
https://www.geeksforgeeks.org/swap-two-nibbles-byte/
1978
Chapter 318
Input : 10
Output : 5
Binary representation of 10 is 1010
After toggling we get 0101
Input : 5
Output : 2
We can toggle a bit by doing XOR of it with 1 (Note that 1 ^ 0 = 1 and 1 ^ 1 = 0).
The idea is to take a number temp with only one bit set. One by one move the only set
bit of temp to left and do XOR of it with n until it crosses MSB (Most Significant Bit) of n.
C++
1979
Chapter 318. Toggle all bits after most significant bit
Java
1980
Chapter 318. Toggle all bits after most significant bit
// corresponding to
// current set bit in
// temp.
n = n ^ temp;
// Move set bit to next
// higher position.
temp = temp << 1;
}
return n;
}
// Driver code
public static void main(String arg[])
{
int n = 10;
n = toggle(n);
System.out.print(n);
}
}
// This code is contributed by Anant Agarwal.
Python3
1981
Chapter 318. Toggle all bits after most significant bit
C#
1982
Chapter 318. Toggle all bits after most significant bit
PHP
<?php
// PHP program to toggle set
// bits starting from MSB
function toggle( &$n)
{
// temporary variable to
// use XOR with one of a n
$temp = 1;
// Run loop until the only
// set bit in temp crosses
// MST of n.
while ($temp <= $n)
{
// Toggle bit of n
// corresponding to
// current set bit in
// temp.
$n = $n ^ $temp;
// Move set bit to next
// higher position.
$temp = $temp << 1;
}
}
// Driver code
$n = 10;
toggle($n);
echo $n;
// This code is contributed by ajit
?>
Output :
1983
Chapter 318. Toggle all bits after most significant bit
The above solution can be optimized to work in O(1) time under the assumption that
numbers are stored in 32 bits.
C++
Java
1984
Chapter 318. Toggle all bits after most significant bit
Python3
1985
Chapter 318. Toggle all bits after most significant bit
def setAllBitsAfterMSB(n):
# This makes sure two bits
# (From MSB and including MSB)
# are set
n |= n>>1
# This makes sure 4 bits
# (From MSB and including MSB)
# are set
n |= n>>2
n |= n>>4
n |= n>>8
n |= n>>16
return n
def toggle(n):
n = n ^ setAllBitsAfterMSB(n)
return n
#Driver code
n = 10
n=toggle(n)
print(n)
# This code is contributed by Anant Agarwal.
C#
1986
Chapter 318. Toggle all bits after most significant bit
PHP
<?php
// PHP program to toggle set
// bits starting from MSB
// Returns a number which
// has all set bits starting
// from MSB of n
function setAllBitsAfterMSB($n)
{
// This makes sure two bits
// (From MSB and including MSB)
// are set
$n |= $n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set
$n |= $n >> 2;
1987
Chapter 318. Toggle all bits after most significant bit
Output :
Source
https://www.geeksforgeeks.org/toggle-bits-significant-bit/
1988
Chapter 319
Input : 10
Output : 0
binary representation 1 0 1 0
after toggle 0 0 0 0
Input : 20
Output : 30
binary representation 1 0 1 0 0
after toggle 1 1 1 1 0
C++
1989
Chapter 319. Toggle all even bits of a number
int evenbittogglenumber(int n)
{
// Genarate number form of 101010
// ..till of same order as n
int res = 0, count = 0;
for (int temp = n; temp > 0; temp >>= 1) {
// if bit is even then generate
// number and or with res
if (count % 2 == 1)
res |= (1 << count);
count++;
}
// return toggled number
return n ^ res;
}
// Driver code
int main()
{
int n = 11;
cout << evenbittogglenumber(n);
return 0;
}
Java
1990
Chapter 319. Toggle all even bits of a number
Python3
1991
Chapter 319. Toggle all even bits of a number
# Driver code
n = 11
print(evenbittogglenumber(n))
#This code is contributed by Nikita Tiwari.
C#
1992
Chapter 319. Toggle all even bits of a number
PHP
<?php
// php code to Toggle all
// even bit of a number
// Returns a number which has
// all even bits of n toggled.
function evenbittogglenumber($n)
{
// Genarate number form of 101010
// ..till of same order as n
$res = 0;
$count = 0;
for ($temp = $n; $temp > 0; $temp >>= 1)
{
// if bit is even then generate
// number and or with res
if ($count % 2 == 1)
$res |= (1 << $count);
$count++;
}
// return toggled number
return $n ^ $res;
}
// Driver code
$n = 11;
echo evenbittogglenumber($n);
// This code is contributed by mits
?>
Output:
Source
https://www.geeksforgeeks.org/toggle-even-bits-number/
1993
Chapter 320
Input : 10
Output : 15
binary representation 1 0 1 0
after toggle 1 1 1 1
Input : 20
Output : 1
binary representation 1 0 1 0 0
after toggle 0 0 0 0 1
C++
1994
Chapter 320. Toggle all odd bits of a number
Java
1995
Chapter 320. Toggle all odd bits of a number
// return toggled number
return n ^ res;
}
// Driver code
public static void main(String args[])
{
int n = 11;
System.out.println(evenbittogglenumber(n));
}
}
/*This code is contributed by Nikita tiwari.*/
Python3
1996
Chapter 320. Toggle all odd bits of a number
print(evenbittogglenumber(n))
# This code is contributed by Nikita Tiwari.
C#
1997
Chapter 320. Toggle all odd bits of a number
PHP
<?php
// php implementation of Toggle
// all odd bit of a number
// Returns a number which has
// all odd bits of n toggled.
function evenbittogglenumber($n)
{
// Genarate number form of 101010...
// ..till of same order as n
$res = 0;
$count = 0;
for ($temp = $n; $temp > 0; $temp >>= 1)
{
// if bit is odd, then generate
// number and or with res
if ($count % 2 == 0)
$res |= (1 << $count);
$count++;
}
// return toggled number
return $n ^ $res;
}
// Driver code
$n = 11;
echo evenbittogglenumber($n);
// This code is contributed by mits
?>
Output :
14
Source
https://www.geeksforgeeks.org/toggle-odd-bits-number/
1998
Chapter 321
Input : n = 4294967295, k = 0
Output : 1
The number 4294967295 in 32 bits has all bits
set. When we toggle all bits except last bit,
we get 1.
Input : n = 1, k = 1
Output : 4294967292
4294967262 has all bits toggled except second
bit from right.
1. Toggle bit at k-th position. We do it by finding a number with only k-th bit set (using
1 << k), then doing bitwise XOR of this number n.
2. Toggle all bits of number obtained above using ~ (Bitwise negation)
1999
Chapter 321. Toggle all the bits of a number except k-th bit.
{
/* 1) Toggle k-th bit by doing n ^ (1 << k)
2) Toggle all bits of the modified number */
return ~(n ^ (1 << k));
}
// Driver code
int main()
{
unsigned int n = 4294967295;
unsigned int k = 0;
printf("%u", toggleAllExceptK( n, k));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/toggle-bits-number-except-k-th-bit/
2000
Chapter 322
Input : n = 17, l = 2, r = 3
Output : 23
(17)10 = (10001)2
(23)10 = (10111)2
The bits in the range 2 to 3 in the binary
representation of 17 are toggled.
Input : n = 50, l = 2, r = 5
Output : 44
1. Calculate num = ((1 << r) – 1) ^ ((1 << (l-1)) – 1). This will produce a number
num having r number of bits and bits in the range l to r are the only set bits.
2. Now, perform n = n ^ num. This will toggle the bits in the range l to r in n.
C/C++
2001
Chapter 322. Toggle bits in the given range
Java
2002
Chapter 322. Toggle bits in the given range
{
int n = 50;
int l = 2, r = 5;
System.out.println(toggleBitsFromLToR(n, l, r));
}
}
// Contributed by Pramod Kumar
Python3
# Python implementation
# to toggle bits in
# the given range
# function to toggle bits
# in the given range
def toggleBitsFromLToR(n,l,r):
# calculating a number
# 'num' having 'r'
# number of bits and
# bits in the range l
# to r are the only set bits
num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
# toggle bits in the
# range l to r in 'n'
# and return the number
return (n ^ num)
# Driver code
n = 50
l = 2
r = 5
print(toggleBitsFromLToR(n, l, r))
# This code is contributed
# by Anant Agarwal.
C#
2003
Chapter 322. Toggle bits in the given range
namespace Toggle
{
public class GFG
{
// Function to toggle bits in the given range
static int toggleBitsFromLToR(int n, int l, int r)
{
// calculating a number 'num' having 'r'
// number of bits and bits in the range l
// to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// toggle bits in the range l to r in 'n'
// and return the number
return (n ^ num);
}
// Driver Code
public static void Main ()
{
int n = 50;
int l = 2, r = 5;
Console.Write(toggleBitsFromLToR(n, l, r));
}
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP implementation
// to toggle bits in
// the given range
// function to toggle bits
// in the given range
function toggleBitsFromLToR($n, $l, $r)
{
// calculating a number
// 'num' having 'r'
// number of bits and
// bits in the range l
// to r are the only
2004
Chapter 322. Toggle bits in the given range
Output:
44
Improved By : vt_m
Source
https://www.geeksforgeeks.org/toggle-bits-given-range/
2005
Chapter 323
Input : 10
Output : 12
Binary representation:- 1 0 1 0
After toggling first and last : 1 1 0 0
Input : 9
Output : 15
Binary representation : 1 0 0 1
After toggling first and last : 1 1 1 1
2006
Chapter 323. Toggle bits of a number except first and last bits
// return set middle bits
int setmiddlebits(int n)
{
// set all bit
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// return middle set bits
// shift by 1 and xor with 1
return (n >> 1) ^ 1;
}
int togglemiddlebits(int n)
{
// if number is 1 then
// simply return
if (n == 1)
return 1;
// xor with
// middle bits
return n ^ setmiddlebits(n);
}
// Driver Code
int main()
{
// Given number
int n = 9;
// print toggle bits
cout<<togglemiddlebits(n);
return 0;
}
Java
2007
Chapter 323. Toggle bits of a number except first and last bits
class GFG {
// return set middle bits
static int setmiddlebits(int n)
{
// set all bit
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// return middle set bits
// shift by 1 and xor with 1
return (n >> 1) ^ 1;
}
static int togglemiddlebits(int n)
{
// if number is 1 then
// simply return
if (n == 1)
return 1;
// XOR with middle bits
return n ^ setmiddlebits(n);
}
// Driver Code
public static void main (String[] args)
{
// Given number
int n = 9;
// print toggle bits
System.out.println(togglemiddlebits(n));
}
}
// This code is contributed by vt_m
Python3
2008
Chapter 323. Toggle bits of a number except first and last bits
# return set middle bits
def setmiddlebits(n):
# set all bit
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
# return middle set bits
# shift by 1 and xor with 1
return (n >> 1) ^ 1
def togglemiddlebits(n):
# if number is 1 then simply return
if (n == 1):
return 1
# xor with middle bits
return n ^ setmiddlebits(n)
# Driver code
n = 9
print(togglemiddlebits(n))
# This code is contributed by Anant Agarwal.
C#
2009
Chapter 323. Toggle bits of a number except first and last bits
// return middle set bits
// shift by 1 and xor with 1
return (n >> 1) ^ 1;
}
static int togglemiddlebits(int n)
{
// if number is 1 then
// simply return
if (n == 1)
return 1;
// XOR with middle bits
return n ^ setmiddlebits(n);
}
// Driver Code
public static void Main ()
{
// Given number
int n = 9;
// print toggle bits
Console.WriteLine(togglemiddlebits(n));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// Php Program to toggle bits
// except first and last bit
// return set middle bits
function setmiddlebits($n)
{
// set all bit
$n |= $n >> 1;
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
2010
Chapter 323. Toggle bits of a number except first and last bits
// return middle set bits
// shift by 1 and xor with 1
return ($n >> 1) ^ 1;
}
function togglemiddlebits($n)
{
// if number is 1 then
// simply return
if ($n == 1)
return 1;
// xor with
// middle bits
return $n ^ setmiddlebits($n);
}
// Driver Code
$n = 9;
// print toggle bits
echo togglemiddlebits($n);
// This code is contributed by ajit
?>
15
Source
https://www.geeksforgeeks.org/toggle-bits-number-expect-first-last-bits/
2011
Chapter 324
Input : "GeekSfOrgEEKs"
Output : "gEEKsFoRGeekS"
Input : "StRinG"
Output : "sTrINg"
TheASCII table is constructed in such way that the binary representation of lowercase letters
is almost identical of binary representation of uppercase letters.
Toggling Case
The integer with 6th LSB as 1 is 32 (0010 0000). Therefore, bitwise XORing of a character
with 32 will toggle the 6th LSB of character and hence, will toggle its case. If character is
upper case, it will be converted to lower case and vice versa.
C
2012
Chapter 324. Toggle case of a string using Bitwise Operators
Java
2013
Chapter 324. Toggle case of a string using Bitwise Operators
{
String str = "CheRrY";
System.out.print("Toggle case: ");
str = toggleCase(str.toCharArray());
System.out.println(str);
System.out.print("Original string: ");
str = toggleCase(str.toCharArray());
System.out.println(str);
}
}
C#
2014
Chapter 324. Toggle case of a string using Bitwise Operators
Output:
Source
https://www.geeksforgeeks.org/toggle-case-string-using-bitwise-operators/
2015
Chapter 325
Input : 10
Output : 3
Binary representation of 10 is
1010. After toggling first and
last bits, we get 0011.
Input : 15
Output : 6
2016
Chapter 325. Toggle first and last bits of a number
Java
2017
Chapter 325. Toggle first and last bits of a number
Python3
2018
Chapter 325. Toggle first and last bits of a number
C#
2019
Chapter 325. Toggle first and last bits of a number
PHP
<?php
// PHP program to toggle first and last
// bits of a number
// Returns a number which has same bit
// count as n and has only first and last
// bits as set.
function takeLandFsetbits($n)
{
// set all the bit of the number
$n |= $n >> 1;
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
2020
Chapter 325. Toggle first and last bits of a number
// Adding one to n now unsets
// all bits and moves MSB to
// one place. Now we shift
// the number by 1 and add 1.
return (($n + 1) >> 1) + 1;
}
function toggleFandLbits(int $n)
{
// if number is 1
if ($n == 1)
return 0;
// take XOR with first and
// last set bit number
return $n ^ takeLandFsetbits($n);
}
// Driver code
$n = 10;
echo toggleFandLbits($n);
// This code is contributed by mits
?>
Output :
Source
https://www.geeksforgeeks.org/toggle-first-last-bits-number/
2021
Chapter 326
Input : n = 21, m = 2
Output : 22
(21)10 = (10101)2
(22)10 = (10110)2
The last two bits in the binary
representation of 21 are toggled.
Input : n = 107, m = 4
Output : 100
1. Calculate num = (1 << m) – 1. This will produce a number num having m number
of bits and all will be set.
2. Now, perform n = n ^ num. This will toggle the last m bits in n.
C++
// C++ implementation to
// toggle the last m bits
#include <bits/stdc++.h>
using namespace std;
2022
Chapter 326. Toggle the last m bits
// function to toggle
// the last m bits
unsigned int toggleLastMBits
(unsigned int n, unsigned int m)
{
// calculating a number
// 'num' having 'm' bits
// and all are set.
unsigned int num = (1 << m) - 1;
// toggle the last m bits
// and return the number
return (n ^ num);
}
// Driver code
int main()
{
unsigned int n = 107;
unsigned int m = 4;
cout << toggleLastMBits(n, m);
return 0;
}
Java
// Java implementation to
// toggle the last m bits
import java.util.*;
import java.lang.*;
public class GfG{
// function to toggle
// the last m bits
public static int toggleLastMBits
(int n, int m)
{
// calculating a number
// 'num' having 'm' bits
// and all are set
int num = (1 << m) - 1;
// toggle the last m bits
// and return the number
2023
Chapter 326. Toggle the last m bits
return (n ^ num);
}
// Driver function
public static void main(String argc[]){
int n = 107;
int m = 4;
n = toggleLastMBits(n, m);
System.out.println(n);
}
}
// This code is contributed by Sagar Shukla.
Python3
# Python implementation to
# toggle the last m bits
# function to toggle
# the last m bits
def toggleLastMBits(n,m):
# calculating a number
# 'num' having 'm' bits
# and all are set.
num = (1 << m) - 1
# toggle the last m bits
# and return the number
return (n ^ num)
# Driver code
n = 107
m = 4
print(toggleLastMBits(n, m))
# This code is contributed
# by Anant Agarwal.
C#
// C# implementation to
// toggle the last m bits
using System;
2024
Chapter 326. Toggle the last m bits
namespace Toggle
{
public class GFG
{
// Function to toggle the last m bits
public static int toggleLastMBits(int n, int m)
{
// Calculating a number 'num' having
// 'm' bits and all are set
int num = (1 << m) - 1;
// Toggle the last m bits
// and return the number
return (n ^ num);
}
// Driver Code
public static void Main() {
int n = 107, m = 4;
n = toggleLastMBits(n, m);
Console.Write(n);
}
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP implementation to
// toggle the last m bits
// function to toggle
// the last m bits
function toggleLastMBits($n, $m)
{
// calculating a number
// 'num' having 'm' bits
// and all are set.
$num = (1 << $m) - 1;
2025
Chapter 326. Toggle the last m bits
Output:
100
Source
https://www.geeksforgeeks.org/toggle-last-m-bits/
2026
Chapter 327
Input : n = 5, k = 1
Output : 4
5 is represented as 101 in binary
and has its first bit 1, so toggling
it will result in 100 i.e. 4.
Input : n = 2, k = 3
Output : 6
Input : n = 75, k = 4
Output : 67
Example :
2027
Chapter 327. Toggling k-th bit of a number
n = 75 and k = 4
temp = 1 << (k-1) = 1 << 3 = 8
Binary Representation of temp = 0..00001000
Binary Representation of n = 0..01001011
Bitwise XOR of two numbers = 0..01000011
C++
Java
// Java program to toogle
// k-th bit of a number
class Toggle
{
static int toggleKthBit(int n, int k)
{
return (n ^ (1 << (k-1)));
}
// main function
public static void main (String[] args)
{
int n = 5, k = 1;
System.out.println(toggleKthBit(n , k));
}
}
Python3
2028
Chapter 327. Toggling k-th bit of a number
C#
// C# program to toogle
// k-th bit of a number
using System;
class GFG {
static int toggleKthBit(int n, int k)
{
return (n ^ (1 << (k-1)));
}
// main function
public static void Main()
{
int n = 5, k = 1;
Console.WriteLine(toggleKthBit(n , k));
}
}
//This code is contributed by Anant Agarwal.
PHP
<?php
// Php program to toggle k-th bit of n
function toggleKthBit($n, $k)
{
return ($n ^ (1 << ($k - 1)));
}
// Driver code
2029
Chapter 327. Toggling k-th bit of a number
$n = 5;
$k = 1;
echo toggleKthBit($n, $k);
// This code is contributed by Ajit
?>
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/toggling-k-th-bit-number/
2030
Chapter 328
For example, consider the graph shown in figure on right side. A TSP tour in the graph is
1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80.
The problem is a famous NP hardproblem. There is no polynomial time know solution for
this problem.
Following are different solutions for the traveling salesman problem.
2031
Chapter 328. Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Naive Solution:
1) Consider city 1 as the starting and ending point.
2) Generate all (n-1)! Permutationsof cities.
3) Calculate cost of every permutation and keep track of minimum cost permutation.
4) Return the permutation with minimum cost.
Time Complexity: Θ(n!)
Dynamic Programming:
Let the given set of vertices be {1, 2, 3, 4,….n}. Let us consider 1 as starting and ending
point of output. For every other vertex i (other than 1), we find the minimum cost path
with 1 as the starting point, i as the ending point and all vertices appearing exactly once.
Let the cost of this path be cost(i), the cost of corresponding Cycle would be cost(i) + dist(i,
1) where dist(i, 1) is the distance from i to 1. Finally, we return the minimum of all [cost(i)
+ dist(i, 1)] values. This looks simple so far. Now the question is how to get cost(i)?
To calculate cost(i) using Dynamic Programming, we need to have some recursive relation
in terms of sub-problems. Let us define a term C(S, i) be the cost of the minimum cost path
visiting each vertex in set S exactly once, starting at 1 and ending at i.
We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset,
then we calculate C(S, i) for all subsets S of size 3 and so on. Note that 1 must be present
in every subset.
For a set of size n, we consider n-2 subsets each of size n-1 such that all subsets don’t have
nth in them.
Using the above recurrence relation, we can write dynamic programming based solution.
There are at most O(n*2n ) subproblems, and each one takes linear time to solve. The total
running time is therefore O(n2 *2n ). The time complexity is much less than O(n!), but still
exponential. Space required is also exponential. So this approach is also infeasible even for
slightly higher number of vertices.
We will soon be discussing approximate algorithms for travelling salesman problem.
Next Article: Traveling Salesman Problem | Set 2
References:
http://www.lsi.upc.edu/~mjserna/docencia/algofib/P07/dynprog.pdf
http://www.cs.berkeley.edu/~vazirani/algorithms/chap6.pdf
Source
https://www.geeksforgeeks.org/travelling-salesman-problem-set-1/
2032
Chapter 329
Input: 12 (00...01100)
Output: 8 (00...01000)
Input: 7 (00...00111)
Output: 6 (00...00110)
Let the input number be n. n-1 would have all the bits flipped after the rightmost set bit
(including the set bit). So, doing n&(n-1) would give us the required result.
#include<stdio.h>
// unsets the rightmost set bit
// of n and returns the result
int fun(unsigned int n)
{
return n & (n - 1);
}
// Driver Code
int main()
{
int n = 7;
printf("The number after unsetting the");
2033
Chapter 329. Turn off the rightmost set bit
Java
Python3
C#
2034
Chapter 329. Turn off the rightmost set bit
PHP
<?php
// unsets the rightmost set bit
// of n and returns the result
function fun($n)
{
return $n & ($n - 1);
}
// Driver Code
$n = 7;
echo "The number after unsetting the".
" rightmost set bit ", fun($n);
// This code is contributed by vt_m.
?>
Output :
2035
Chapter 329. Turn off the rightmost set bit
Improved By : vt_m
Source
https://www.geeksforgeeks.org/turn-off-the-rightmost-set-bit/
2036
Chapter 330
Two odd occurring elements in an array where all other occur even times - GeeksforGeeks
Given an array where all elements appear even number of times except two, print the two
odd occurring elements. It may be assumed that the size of array is at-least two.
Examples:
Input : arr[] = {15, 10, 10, 50 7, 5, 5, 50, 50, 50, 50, 50}
Output : 7 15
A simple solution is to use two nested loops. The outer loop traverses through all elements.
The inner loop counts occurrences of the current element. We print the elements whose
counts of occurrences are odd. Time complexity if this solution is O(n2 )
A better solution is to use hashing. Time complexity of this solution is O(n) but it requires
extra space.
An efficient solution is to use bitwise operators. The idea is based on approach used in
two missing elements and two repeating elements.
C++
2037
Chapter 330. Two odd occurring elements in an array where all other occur even times
Java
2038
Chapter 330. Two odd occurring elements in an array where all other occur even times
2039
Chapter 330. Two odd occurring elements in an array where all other occur even times
4, 4, 5 };
int n = arr.length;
printOdds(arr, n);
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
2040
Chapter 330. Two odd occurring elements in an array where all other occur even times
# Driver code
arr = [2, 3, 3, 4, 4, 5 ]
n = len(arr)
printOdds(arr, n)
# This code is contributed
# by Smitha
C#
2041
Chapter 330. Two odd occurring elements in an array where all other occur even times
else
y = y ^ arr[i];
}
// XOR of two different
// sets are our required
// numbers.
Console.WriteLine(x + " " + y);
}
// Driver code
public static void Main()
{
int []arr = { 2, 3, 3,
4, 4, 5 };
int n = arr.Length;
printOdds(arr, n);
}
}
// This code is contributed by
// Akanksha Rai(Abby_akku)
PHP
Output:
5 2
Source
https://www.geeksforgeeks.org/two-odd-occurring-elements-array-occur-even-times/
2042
Chapter 331
Unique element in an array where all elements occur k times except one - GeeksforGeeks
Given an array which contains all elements occurring k times, but one occurs only once.
Find that unique element.
Examples:
A Simple Solution is to use two nested loops. The outer loop picks an element one by one
starting from the leftmost element. The inner loop checks if the element is present k times
or not. If present, then ignores the element, else prints the element.
Time Complexity of above solution is O(n2 ). We can Use Sorting to solve the problem
in O(nLogn) time. The idea is simple, first sort the array so that all occurrences of every
element become consecutive. Once the occurrences become consecutive, we can traverse the
sorted array and print the unique element in O(n) time.
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the
given array from left to right and keep track of visited elements in a hash table. Finally
print the element with count 1.
2043
Chapter 331. Unique element in an array where all elements occur k times except one
The hashing based solution requires O(n) extra space. We can use bitwise AND to find
the unique element in O(n) time and constant extra space.
2044
Chapter 331. Unique element in an array where all elements occur k times except one
Output:
Source
https://www.geeksforgeeks.org/find-unique-element-element-occurs-k-times-except-one/
2045
Chapter 332
Input : n = 42, l = 2, r = 5
Output : 32
(42)10 = (101010)2
(32)10 = (100000)2
The bits in the range 2 to 5 in the binary
representation of 42 have been unset.
Input : n = 63, l = 1, r = 4
Output : 48
1. Calculate num = (1 << (sizeof(int) * 8 – 1)) – 1. This will produce the highest
positive integer num. All the bits in num will be set.
2. Toggle bits in the range l to r in num. Refer this post.
3. Now, perform n = n & num. This will unset the bits in the range l to r in n.
4. Return n.
Note: The sizeof(int) has been used as input is of int data type. For large inputs you
can use long int or long long int datatypes in place of int.
C/C++
2046
Chapter 332. Unset bits in the given range
Java
2047
Chapter 332. Unset bits in the given range
class GFG
{
// Function to toggle bits in the given range
static int toggleBitsFromLToR(int n, int l, int r)
{
// calculating a number 'num' having 'r' number of bits
// and bits in the range l to r are the only set bits
int num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1);
// toggle the bits in the range l to r in 'n'
// and return the number
return (n ^ num);
}
// Function to unset bits in the given range
static int unsetBitsInGivenRange(int n, int l, int r)
{
// 'num' is the highest positive integer number
// all the bits of 'num' are set
int num = (1 << (4 * 8 - 1)) - 1;
// toggle the bits in the range l to r in 'num'
num = toggleBitsFromLToR(num, l, r);
// unset the bits in the range l to r in 'n'
// and return the number
return (n & num);
}
// driver program
public static void main (String[] args)
{
int n = 42;
int l = 2, r = 5;
System.out.println(unsetBitsInGivenRange(n, l, r));
}
}
// Contributed by Pramod Kumar
Python3
2048
Chapter 332. Unset bits in the given range
PHP
<?php
// PHP implementation to unset
// bits in the given range
// Function to toggle bits
// in the given range
2049
Chapter 332. Unset bits in the given range
Output:
2050
Chapter 332. Unset bits in the given range
32
Improved By : Sam007
Source
https://www.geeksforgeeks.org/unset-bits-given-range/
2051
Chapter 333
Input : n = 10, m = 2
Output : 8
(10)10 = (1010)2
(8)10 = (1000)2
The last two bits in the binary
representation of 10 have been unset.
Input : n = 150, m = 4
Output : 144
1. Calculate num = (1 << (sizeof(int) * 8 – 1)) – 1. This will produce the highest
positive integer num. All the bits in num will be set.
2. Toggle the last m bits in num. Refer this post.
3. Now, perform n = n & num. This will unset the last m bits in n.
4. Return n.
Note: The sizeof(int) has been used as input is of int data type. For large inputs you
can use long int or long long int datatypes in place of int.
C++
2052
Chapter 333. Unset the last m bits
Python3
2053
Chapter 333. Unset the last m bits
# calculating a number 'num'
# having 'm' bits and all are set
num = (1 << m) - 1
# toggle the last m bits
# and return the number
return (n ^ num)
# function to unset bits
# the last m bits
def unsetLastMBits(n, m):
# 'num' is the highest positive integer
# number all the bits of 'num' are set
num = (1 << (sys.getsizeof(int) * 8 - 1)) - 1
# toggle the last 'm' bits in 'num'
num = toggleLastMBits(num, m)
# unset the last 'm' bits in 'n'
# and return the number
return (n & num)
# Driven code
n = 150
m = 4
print (unsetLastMBits(n, m))
# This code is contributed by "rishabh_jain".
PHP
<?php
// php implementation to unset
// bits the last m bits
// function to toggle
// the last m bits
function toggleLastMBits($n, $m)
{
// calculating a number 'num'
// having 'm' bits
// and all are set
$num = (1 << $m) - 1;
// toggle the last m bits
2054
Chapter 333. Unset the last m bits
Output:
144
Source
https://www.geeksforgeeks.org/unset-last-m-bits/
2055
Chapter 334
Input : N = 7
L=2
R = 23
Output : 23
Explanation : When X = 16, we get 7 � 16 = 23 which is the maximum value
for all X � [2, 23].
Input : N = 10
L=5
R = 12
Output : 15
Explanation : When X = 5, we get 10 � 5 = 15 which is the maximum value for
all X � [5, 12].
Brute force approach: We can solve this problem using brute force approach by looping
over all integers over the range [L, R] and taking their XOR with N, while keeping a record
of the maximum result encountered so far. The complexity of this algorithm will be O(R –
L), and it is not feasible when the input variables approach high values such as 109 .
Efficient approach: Since the XOR of two bits is 1 if and only if they are complementary
to each other, we need X to have complementary bits to that of N to have the maximum
value. We will iterate from the largest bit (log2 (R)th bit) to the lowest (0th bit). The
following two cases can arise for each bit:
2056
Chapter 334. Value in a given range with maximum XOR
1. If the bit is not set, i.e. 0, we will try to set it in X. If setting this bit to 1 results in
X exceeding R, then we will not set it.
2. If the bit is set, i.e. 1, then we will try to unset it in X. If the current value of X
is already greater than or equal to L, then we can safely unset the bit. In the other
case, we will check if setting all of the next sits is enough to keep X >= L. If not,
then we are required to set the current bit. Observe that setting all of the next bits is
equivalent to adding (1 << b) – 1, where b is the current bit.
Java
2057
Chapter 334. Value in a given range with maximum XOR
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Function to calculate the maximum value of
// N ^ X, where X is in the range [L, R]
static int maximumXOR(int n, int l, int r)
{
int x = 0;
for (int i = (int)(Math.log(r)/Math.log(2)); i >= 0; --i)
{
if ((n & (1 << i))>0) // Set bit
{
if ((x > r) || (x + (1 << i) - 1 < l))
x ^= (1 << i);
}
else // Unset bit
{
if ((x ^ (1 << i)) <= r)
x ^= (1 << i);
}
}
return n ^ x;
}
// Driver function
public static void main(String args[])
{
int n = 7, l = 2, r = 23;
System.out.println( "The output is " + maximumXOR(n, l, r));
}
}
// This code is Contributed by tufan_gupta2000
Output:
The output is 23
Improved By : tufan_gupta2000
2058
Chapter 334. Value in a given range with maximum XOR
Source
https://www.geeksforgeeks.org/value-in-a-given-range-with-maximum-xor/
2059
Chapter 335
Approach:
Grundy number for each pile is calculated based on the number of stones.To compensate
2060
Chapter 335. Variation in Nim Game
the zero move we will have to modify grundy values we used in standard nim game.
If pile size is odd; grundy number is size+1 and
if pile size is even; grundy number is size-1.
We XOR all the grundy number values to check if final Grundy number(G) of game is non
zero or not to decide who is winner of game.
Explanation:
Grundy number of a state is the smallest positive integer that cannot be reached in
one valid move.
So, we need to calculate mex value for each n, bottom up wise so that we can induce the
grundy number for each n. where n is the pile size and valid move is the move that will lead
the current player to winning state.
Winning state: A tuple of values from where the current player will win the game no
matter what opponent does. (If G!=0)
Losing state: A tuple of values from where the current player will loose the game no matter
what opponent does. (If G=0)
2061
Chapter 335. Variation in Nim Game
C++
2062
Chapter 335. Variation in Nim Game
Java
2063
Chapter 335. Variation in Nim Game
// This code is contributed by Anant Agarwal.
Python3
C#
2064
Chapter 335. Variation in Nim Game
2065
Chapter 335. Variation in Nim Game
// This code is contributed by vt_m.
PHP
<?php
// php program for the variation
// in nim game
// Function to return final
// grundy Number(G) of game
function solve($p,$n)
{
$G = 0;
for ($i = 0; $i < $n; $i++)
{
// if pile size is odd
if ($p[$i] & 1)
// We XOR pile size+1
$G ^= ($p[$i] + 1);
else // if pile size is even
// We XOR pile size-1
$G ^= ($p[$i] - 1);
}
return $G;
}
// Driver Code
// Game with 3 piles
$n = 3;
// pile with different sizes
$p= array( 32, 49, 58 );
// Function to return result of game
$res = solve($p, $n);
if ($res == 0) // if G is zero
echo "Player 2 wins";
else // if G is non zero
echo "Player 1 wins";
// This code is contributed by mits
?>
2066
Chapter 335. Variation in Nim Game
Output:
Player 1 wins
Source
https://www.geeksforgeeks.org/variation-nim-game/
2067
Chapter 336
Input : N = 3
Output : 3
3 can be represented as (1+1+1), (2+1), (1+2).
Input : N = 5
Output : 8
For N = 1, answer is 1.
For N = 2. (1 + 1), (2), answer is 2.
For N = 3. (1 + 1 + 1), (2 + 1), (1 + 2), answer is 3.
For N = 4. (1 + 1 + 1 + 1), (2 + 1 + 1), (1 + 2 + 1), (1 + 1 + 2), (2 + 2) answer is 5.
And so on.
It can be observe that it form Fibonacci Series. So, the number of ways of representing N
as a sum of 1s and 2s is (N + 1)th Fibonacci number.
How ?
We can easily see that the recursive function is exactly same as Fibonacci Numbers. To
obtain the sum of N, we can add 1 to N – 1. Also, we can add 2 to N – 2. And only 1
and 2 are allowed to make the sum N. So, to obtain sum N using 1s and 2s, total ways are:
number of ways to obtain (N – 1) + number of ways to obtain (N – 2).
We can find N’th Fibonacci Number in O(Log n) time. Please refer method 5 of this post.
Below is C++ implementation of this approach:
2068
Chapter 336. Ways to represent a number as a sum of 1’s and 2’s
2069
Chapter 336. Ways to represent a number as a sum of 1’s and 2’s
int n = 5;
cout << countWays(n) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/ways-to-represent-a-number-as-a-sum-of-1s-and-2s/
2070
Chapter 337
Ways to split array into two groups of same XOR value - GeeksforGeeks
Given an array A of n integers. The task is to count the number of ways to split given
array elements into two disjoint groups, such that XOR of elements of each group is equal.
Examples:
Input : A[] = { 1, 2, 3 }
Output : 3
{(1), (2, 3)}, {(2), (1, 3)}, {(3), (1, 2)}
are three ways with equal XOR value of two
groups.
Input : A[] = { 5, 2, 3, 2 }
Output : 0
Let’s denote XOR between all elements in the first group as G1 and XOR between all
elements in the second group as G2 . Now, the following relation is always correct: G1 � G2
= A1 � A2 � …. � An .
So for G1 = G2 , xor between all elements of array A is equal to 0. So, in that case, answer
will be (2n – 2)/2 = (2n-1 – 1). In second case, when XOR between all elements isn’t 0, we
can not split array. Answer will be 0.
C++
2071
Chapter 337. Ways to split array into two groups of same XOR value
#include<bits/stdc++.h>
using namespace std;
// Return the count number of ways to split
// array into two groups such that each group
// has equal XOR value.
int countgroup(int a[], int n)
{
int xs = 0;
for (int i = 0; i < n; i++)
xs = xs ^ a[i];
// We can split only if XOR is 0. Since
// XOR of all is 0, we can consider all
// subsets as one group.
if (xs == 0)
return (1 << (n-1)) - 1;
return 0;
}
// Driver Program
int main()
{
int a[] = { 1, 2, 3 };
int n = sizeof(a)/sizeof(a[0]);
cout << countgroup(a, n) << endl;
return 0;
}
Java
2072
Chapter 337. Ways to split array into two groups of same XOR value
Python3
2073
Chapter 337. Ways to split array into two groups of same XOR value
C#
PHP
<?php
// PHP Program to count number
// of ways to split array into
// two groups such that each
// group has equal XOR value
// Return the count number of
2074
Chapter 337. Ways to split array into two groups of same XOR value
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/ways-split-array-two-groups-xor-value/
2075
Chapter 338
What are the differences between bitwise and logical AND operators in C/C++? - Geeks-
forGeeks
A Bitwise And operator is represented as ‘&’ and a logical operator is represented as ‘&&’.
Following are some basic differences between the two operators.
a) The logical and operator ‘&&’ expects its operands to be boolean expressions (either 1
or 0) and returns a boolean value.
The bitwise and operator ‘&’ works on Integral (short, int, unsigned, char, bool, unsigned
char, long) values and return Integral value.
int main()
{
int x = 3; //...0011
int y = 7; //...0111
// A typical use of '&&'
if (y > 1 && y > x)
printf("y is greater than 1 AND y\n");
// A typical use of '&'
int z = x & y; // 0011
printf ("z = %d", z);
return 0;
}
2076
Chapter 338. What are the differences between bitwise and logical AND operators in
C/C++?
Output
b) If an integral value is used as an operand for ‘&&’ which is supposed to work on boolean
values, following rule is used in C.
…..A zero is considered as false and non-zero is considered as true.
For example in the following program x and y are considered as 1.
Output
It is compiler error to use non-integral expression as operand for bitwise &. For example
the following program shows compiler error.
Output:
c) The ‘&&’ operator doesn’t evaluate second operand if first operand becomes false. Simi-
larly ‘||’ doesn’t evaluate second operand when first operand becomes true. The bitwise ‘&’
and ‘|’ operators always evaluate their operands.
2077
Chapter 338. What are the differences between bitwise and logical AND operators in
C/C++?
int main()
{
int x = 0;
// 'Geeks in &&' is NOT printed because x is 0
printf("%d\n", (x && printf("Geeks in && ")) );
// 'Geeks in &' is printed
printf("%d\n", (x & printf("Geeks in & ")) );
return 0;
}
Output:
0
Geeks in & 0
The same differences are there between logical OR ‘||’ and bitwise OR ‘|’.
This article is contributed by Ujjwal Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/what-are-the-differences-between-bitwise-and-logical-and-operators-in-cc/
2078
Chapter 339
Write a function that returns 2 for input 1 and returns 1 for 2 - GeeksforGeeks
Write a function which returns 1 that 2 is passed and return 2 when 1 is passed.
Source: Adobe Interview Experience | Set 19 (For MTS)
A simple solution is to compare the passed value with 1 and 2.
int invert(int x)
{
if (x == 1) return 2;
else return 1;
}
int invertSub(int x)
{
return (3-x);
}
int invertXOR(int x)
{
return (x ^ 1 ^ 2);
}
This article is contributed by Anuj. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
2079
Chapter 339. Write a function that returns 2 for input 1 and returns 1 for 2
Source
https://www.geeksforgeeks.org/write-function-returns-2-input-1-returns-1-2/
2080
Chapter 340
Input : n = 1
Output : 2147483648
On a machine with size of unsigned
bit as 32. Reverse of 0....001 is
100....0.
Input : n = 2147483648
Output : 1
Method1 – Simple
Loop through all the bits of an integer. If a bit at ith position is set in the i/p no. then
set the bit at (NO_OF_BITS – 1) – i in o/p. Where NO_OF_BITS is number of bits
present in the given number.
2081
Chapter 340. Write an Efficient C Program to Reverse Bits of a Number
if(temp)
reverse_num |= (1 << ((NO_OF_BITS - 1) - i));
}
return reverse_num;
}
/* Driver function to test above function */
int main()
{
unsigned int x = 2;
printf("%u", reverseBits(x));
getchar();
}
Above program can be optimized by removing the use of variable temp. See below the
modified code.
2082
Chapter 340. Write an Efficient C Program to Reverse Bits of a Number
while(num)
{
reverse_num <<= 1;
reverse_num |= num & 1;
num >>= 1;
count--;
}
reverse_num <<= count;
return reverse_num;
}
int main()
{
unsigned int x = 1;
printf("%u", reverseBits(x));
getchar();
}
Source
https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/
2083
Chapter 341
Algorithm: isMutlipleOf3(n)
1) Make n positive if n is negative.
2) If number is 0 then return 1
3) If number is 1 then return 0
4) Initialize: odd_count = 0, even_count = 0
5) Loop while n != 0
a) If rightmost bit is set then increment odd count.
b) Right-shift n by 1 bit
2084
Chapter 341. Write an Efficient Method to Check if a Number is Multiple of 3
Proof:
Above can be proved by taking the example of 11 in decimal numbers. (In this context 11
in decimal numbers is same as 3 in binary numbers)
If difference between sum of odd digits and even digits is multiple of 11 then decimal number
is multiple of 11. Let’s see how.
Let’s take the example of 2 digit numbers in decimal
AB = 11A -A + B = 11A + (B – A)
So if (B – A) is a multiple of 11 then is AB.
Let us take 3 digit numbers.
ABC = 99A + A + 11B – B + C = (99A + 11B) + (A + C – B)
So if (A + C – B) is a multiple of 11 then is (ABC)
Let us take 4 digit numbers now.
ABCD = 1001A + D + 11C – C + 999B + B – A
= (1001A – 999B + 11C) + (D + B – A -C )
So, if (B + D – A – C) is a multiple of 11 then is ABCD.
This can be continued for all decimal numbers.
Above concept can be proved for 3 in binary numbers in the same way.
C++
2085
Chapter 341. Write an Efficient Method to Check if a Number is Multiple of 3
while(n)
{
/* If odd bit is set then
increment odd counter */
if(n & 1)
odd_count++;
n = n>>1;
/* If even bit is set then
increment even counter */
if(n & 1)
even_count++;
n = n>>1;
}
return isMultipleOf3(abs(odd_count - even_count));
}
/* Program to test function isMultipleOf3 */
int main()
{
int num = 24;
if (isMultipleOf3(num))
printf("%d is multiple of 3", num);
else
printf("%d is not a multiple of 3", num);
return 0;
}
Java
2086
Chapter 341. Write an Efficient Method to Check if a Number is Multiple of 3
Python3
2087
Chapter 341. Write an Efficient Method to Check if a Number is Multiple of 3
even_count = 0
# Make no positive if +n is multiple of 3
# then is -n. We are doing this to avoid
# stack overflow in recursion
if(n < 0):
n = -n
if(n == 0):
return 1
if(n == 1):
return 0
while(n):
# If odd bit is set then
# increment odd counter
if(n & 1):
odd_count += 1
n = n >> 1
# If even bit is set then
# increment even counter
if(n & 1):
even_count += 1
n = n >> 1
return isMultipleOf3(abs(odd_count - even_count))
# Program to test function isMultipleOf3
num = 24
if (isMultipleOf3(num)):
print(num, 'is multiple of 3')
else:
print(num, 'is not a multiple of 3')
# This code is contributed by Danish Raza
C#
// C# program to check if
// n is a multiple of 3
using System;
class GFG {
// Function to check if n
// is a multiple of 3
static int isMultipleOf3(int n)
2088
Chapter 341. Write an Efficient Method to Check if a Number is Multiple of 3
{
int odd_count = 0, even_count = 0;
/* Make no positive if +n is multiple
of 3 then is -n. We are doing this to
avoid stack overflow in recursion*/
if (n < 0) n = -n;
if (n == 0) return 1;
if (n == 1) return 0;
while (n != 0) {
/* If odd bit is set then
increment odd counter */
if ((n & 1) != 0)
odd_count++;
n = n >> 1;
/* If even bit is set then
increment even counter */
if ((n & 1) != 0)
even_count++;
n = n >> 1;
}
return isMultipleOf3(Math.Abs(odd_count - even_count));
}
// Driver Code
public static void Main()
{
int num = 24;
if (isMultipleOf3(num) != 0)
Console.Write(num + " is multiple of 3");
else
Console.Write(num + " is not a multiple of 3");
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to check if n
2089
Chapter 341. Write an Efficient Method to Check if a Number is Multiple of 3
// is a multiple of 3
// Function to check if n
// is a multiple of 3
function isMultipleOf3( $n)
{
$odd_count = 0;
$even_count = 0;
// Make no positive if +n
// is multiple of 3 then is -n.
// We are doing this to avoid
// stack overflow in recursion
if($n < 0) $n = -$n;
if($n == 0) return 1;
if($n == 1) return 0;
while($n)
{
// If odd bit is set then
// increment odd counter
if($n & 1)
$odd_count++;
$n = $n>>1;
// If even bit is set then
// increment even counter
if($n & 1)
$even_count++;
$n = $n >> 1;
}
return isMultipleOf3(abs($odd_count -
$even_count));
}
// Driver Code
$num = 24;
if (isMultipleOf3($num))
echo $num, "is multiple of 3";
else
echo $num,"is not a multiple of 3";
// This code is contributed by vt_m.
?>
Output :
2090
Chapter 341. Write an Efficient Method to Check if a Number is Multiple of 3
24 is multiple of 3
Related Articles:
Check divisibility in a binary stream
DFA based division
Improved By : Deepak Koli, vt_m
Source
https://www.geeksforgeeks.org/write-an-efficient-method-to-check-if-a-number-is-multiple-of-3/
2091
Chapter 342
#include <stdio.h>
/* implementation of strcmp that ignores cases */
int ic_strcmp(char *s1, char *s2)
{
int i;
for (i = 0; s1[i] && s2[i]; ++i)
{
/* If characters are same or inverting the
6th bit makes them same */
2092
Chapter 342. Write your own strcmp that ignores cases
Output:
ret: 1
ret: -1
ret: -1
ret: -1
ret: 0
ret: 0
This article is compiled by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/write-your-own-strcmp-which-ignores-cases/
2093
Chapter 343
It is reverse of XOR but we can’t implement it directly so this is the program for implement
XNOR
Examples:
Input : 10 20
Output : 1
Binary of 20 is 10100
Binary of 10 is 1010
So the XNOR is 00001
So output is 1
Input : 10 10
Output : 15
Binary of 10 is 1010
Binary of 10 is 1010
So the XNOR is 1111
So output is 15
2094
Chapter 343. XNOR of two numbers
First Method:- (O(logn)) In this solution we check one bit at a time. If two bits are
same, we put 1 in result, else we put 0.
Let’s understand it with below code
C++
2095
Chapter 343. XNOR of two numbers
Java
2096
Chapter 343. XNOR of two numbers
Python3
2097
Chapter 343. XNOR of two numbers
if (a == 0 and b == 0) :
return 1;
# for last bit of a
a_rem = 0
# for last bit of b
b_rem = 0
# counter for count bit and
# set bit in xnor num
count = 0
# for make new xnor number
xnornum = 0
# for set bits in new xnor
# number
while (a!=0) :
# get last bit of a
a_rem = a & 1
# get last bit of b
b_rem = b & 1
# Check if current two
# bits are same
if (a_rem == b_rem):
xnornum |= (1 << count)
# counter for count bit
count=count+1
a = a >> 1
b = b >> 1
return xnornum;
# Driver method
a = 10
b = 50
print(xnor(a, b))
# This code is contributed by Gitanjali
C#
2098
Chapter 343. XNOR of two numbers
// C# program to find
// XNOR of two numbers
using System;
public class GfG {
public static int xnor(int a, int b)
{
// Make sure a is larger
if (a < b) {
// swapping a and b;
int t = a;
a = b;
b = t;
}
if (a == 0 && b == 0)
return 1;
// for last bit of a
int a_rem = 0;
// for last bit of b
int b_rem = 0;
// counter for count bit
// and set bit in xnornum
int count = 0;
// to make new xnor number
int xnornum = 0;
// for set bits in new xnor number
while (true) {
// get last bit of a
a_rem = a & 1;
// get last bit of b
b_rem = b & 1;
// Check if current two bits are same
if (a_rem == b_rem)
xnornum |= (1 << count);
// counter for count bit
count++;
a = a >> 1;
b = b >> 1;
2099
Chapter 343. XNOR of two numbers
if (a < 1)
break;
}
return xnornum;
}
// Driver function
public static void Main()
{
int a = 10, b = 50;
Console.WriteLine(xnor(a, b));
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to find
// XNOR of two numbers
// log(n) solution
function xnor($a, $b)
{
// Make sure a is larger
if ($a < $b)
list($a, $b) = array($b, $a);
if ($a == 0 && $b == 0)
return 1;
// for last bit of a
$a_rem = 0;
// for last bit of b
$b_rem = 0;
// counter for count bit
// and set bit in xnornum
$count = 0;
// to make new xnor number
$xnornum = 0;
// for set bits in
// new xnor number
2100
Chapter 343. XNOR of two numbers
while ($a)
{
// get last bit of a
$a_rem = $a & 1;
// get last bit of b
$b_rem = $b & 1;
// Check if current two
// bits are same
if ($a_rem == $b_rem)
$xnornum |= (1 << $count);
// counter for count bit
$count++;
$a = $a >> 1;
$b = $b >> 1;
}
return $xnornum;
}
// Driver code
$a = 10;
$b = 50;
echo xnor($a, $b);
// This code is contributed by mits.
?>
Output:
C++
2101
Chapter 343. XNOR of two numbers
2102
Chapter 343. XNOR of two numbers
Java
2103
Chapter 343. XNOR of two numbers
Python
2104
Chapter 343. XNOR of two numbers
C#
2105
Chapter 343. XNOR of two numbers
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return i ^ n;
}
// Returns XNOR of num1 and num2
static int xnor(int num1, int num2)
{
// if num2 is greater then
// we swap this number in num1
if (num1 < num2)
{
int temp = num1;
num1 = num2;
num2 = temp;
}
num1 = togglebit(num1);
return num1 ^ num2;
}
// Driver program
public static void Main()
{
int a = 10, b = 20;
Console.WriteLine(xnor(a, b));
}
}
// This code is contributed by vt_m
2106
Chapter 343. XNOR of two numbers
PHP
<?php
// PHP program to find XNOR
// of two numbers.
// Please refer below post
// for details of this function
// https://www.geeksforgeeks.org/toggle-bits-significant-bit/
function togglebit($n)
{
if ($n == 0)
return 1;
// Make a copy of n as we are
// going to change it.
$i = $n;
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
$n |= $n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
return $i ^ $n;
}
// Returns XNOR of num1 and num2
function XNOR($num1, $num2)
{
// if num2 is greater then
// we swap this number in num1
if ($num1 < $num2)
list($num1, $num2)=array($num2, $num1);
$num1 = togglebit($num1);
2107
Chapter 343. XNOR of two numbers
return $num1 ^ $num2;
}
// Driver code
$num1 = 10;
$num2 = 20;
echo XNOR($num1, $num2);
// This code is contributed by Smitha.
?>
Output :
Source
https://www.geeksforgeeks.org/xnor-two-numbers/
2108
Chapter 344
Input : 5
Output : 3
Binary representation : 101
Count of 0s = 1,
Count of 1s = 2
1 XOR 2 = 3.
Input : 7
Output : 3
Binary representation : 111
Count of 0s = 0
Count of 1s = 3
0 XOR 3 = 3.
The idea is simple, we traverse through all bits of a number, count 0s and 1s and finally
return XOR of two counts.
C++
2109
Chapter 344. XOR counts of 0s and 1s in binary representation
Java
2110
Chapter 344. XOR counts of 0s and 1s in binary representation
Python3
C#
2111
Chapter 344. XOR counts of 0s and 1s in binary representation
Output:
One observation is, for a number of the form 2^x – 1, the output is always x. We can
directly produce answer for this case by first checking n+1 is apower of two or not.
Source
https://www.geeksforgeeks.org/xor-counts-0s-1s-binary-representation/
2112
Chapter 345
Suppose the password is ‘abcd’ then the hexadecimal text is calculated as a1d0a1d by
XORing the password with itself N times i.e. 4 times in this case.
Similarly if the password is ‘636f646572’, then
2113
Chapter 345. XOR Encryption by Shifting Plaintext
Input : a1d0a1d
Output : abcd
abcd once coded will return a1d0a1d
Input : 653cae8da8edb426052
Output : 636f646572
Approach : The key ingredient in encrypting and decrypting is in the properties of XOR.
XOR is a bitwise operation where the result is 0 if the two possible inputs are same but 1
when the inputs are different. The XOR table is given below for reference :
Inputs
Outputs
X
Y
Z
0
0
0
0
2114
Chapter 345. XOR Encryption by Shifting Plaintext
1
1
1
0
1
1
1
0
An important and useful property of XOR that is widely popular in cryptography is that in
case of multiple XORing of numbers (say M numbers), if we know only the M – 1 numbers
(one is unknown) along with the XOR result then, we can easily calculate the missing
number by XORing the known numbers and the XOR result. This property is discussed
with the following hexadecimal numbers :
We shall be using the above listed property the most in course of this problem. Now, if we
look at the encryption diagram of ‘abcd’ at the base it is just the repeated XORing of the
digits. The rightmost digit is d and the rightmost digit of the ‘abcd’ is d as well so the last
digit of both plaintext and hexstring is the same. The next digit is 1 which is calculated
by XORing the second right digit of abcd and the previous digit i.e. 1 = d ^ c using the
property we know the plain text digit can be deduced as d ^ 1 = c. Similarly, the next
digit is a which is found by d ^ c ^ b = a. We only need to do this till the half of the hex
string as the rest is symmetrical so they are not required.
# Implementation in Python 3
2115
Chapter 345. XOR Encryption by Shifting Plaintext
# Hex String variable
hex_s = '653cae8da8edb426052'
# Plain text variable
plain = ''
# variable to store the XOR
# of previous digits
x = 0
l = len(hex_s)
# Loop for loop from the end to
# the mid section of the string
for i in range(l - 1, int(l / 2) - 1, -1):
# calculation of the plaintext digit
y = x^int(hex_s[i], 16)
# calculation of XOR chain
x = x^y
plain = hex(y)[-1] + plain
print(plain)
Output:
636f646572
Source
https://www.geeksforgeeks.org/xor-encryption-shifting-plaintext/
2116
Chapter 346
Input :1, 2
Output :6
A Naive approach is to run two loops. Consider each and every pair, take their sum and
calculate the xor value of the sum of all the pairs.
An Efficient approach is based upon the fact that xor of same values is 0.
All the pairs like (a[i], a[j]) and (a[j], a[i]) will have same sum. So, their xor values will be
0. Only the pairs like (a[i], a[i]) will give the different result. So, take the xor of all the
elements of given array and multiply it by 2.
C++
2117
Chapter 346. XOR of Sum of every possible pair of an array
#include <bits/stdc++.h>
using namespace std;
// Function to find XOR of sum
// of all pairs
int findXor(int arr[], int n)
{
// Calculate xor of all the elements
int xoR = 0;
for (int i = 0; i < n; i++) {
xoR = xoR ^ arr[i];
}
// Return twice of xor value
return xoR * 2;
}
// Drivers code
int main()
{
int arr[3] = { 1, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findXor(arr, n);
return 0;
}
Java
2118
Chapter 346. XOR of Sum of every possible pair of an array
}
// Return twice of xor value
return xoR * 2;
}
// Drivers code
public static void main (String[] args)
{
int arr[] = { 1, 5, 6 };
int n = arr.length;
System.out.println( findXor(arr, n));
}
}
// This code is contributed by anuj_67.
Python3
C#
2119
Chapter 346. XOR of Sum of every possible pair of an array
PHP
<?php
// PHP program to find XOR
// of sum of every possible
// pairs in an array
// Function to find XOR
// of sum of all pairs
function findXor($arr, $n)
{
// Calculate xor of
// all the elements
2120
Chapter 346. XOR of Sum of every possible pair of an array
$xoR = 0;
for ($i = 0; $i < $n; $i++)
{
$xoR = $xoR ^ $arr[$i];
}
// Return twice
// of xor value
return $xoR * 2;
}
// Driver code
$arr = array(1, 5, 6);
$n = count($arr);
echo findXor($arr, $n);
// This code is contributed
// by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/xor-sum-every-possible-pair-array/
2121
Chapter 347
2122
Chapter 347. XOR of all subarray XORs | Set 2
C++
2123
Chapter 347. XOR of all subarray XORs | Set 2
{
int arr[] = {3, 5, 2, 4, 6};
int N = sizeof(arr) / sizeof(arr[0]);
cout << getTotalXorOfSubarrayXors(arr, N);
return 0;
}
Java
2124
Chapter 347. XOR of all subarray XORs | Set 2
C#
PHP
<?php
// PHP program to get total
// xor of all subarray xors
2125
Chapter 347. XOR of all subarray XORs | Set 2
// Returns XOR of all subarray xors
function getTotalXorOfSubarrayXors($arr, $N)
{
// if even number of terms
// are there, all numbers
// will appear even number
// of times. So result is 0.
if ($N % 2 == 0)
return 0;
// else initialize result
// by 0 as (a xor 0 = a)
$res = 0;
for ($i = 0; $i < $N; $i += 2)
$res ^= $arr[$i];
return $res;
}
// Driver Code
$arr = array(3, 5, 2, 4, 6);
$N = count($arr);
echo getTotalXorOfSubarrayXors($arr, $N);
// This code is contributed by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/xor-subarray-xors-set-2/
2126
Chapter 348
XOR of two numbers after making length of their binary representations equal - Geeks-
forGeeks
Given two numbers say a and b. Print their XOR after making the lengths of their binary
representation equal by adding trailing zeros to the binary representation of smaller one.
Examples :
Input : a = 13, b = 5
Output : 7
Explanation : Binary representation of 13 is 1101 and
of 5 is 101. As the length of "101" is smaller,
so add a '0' to it making it "1010', to make
the length of binary representations equal.
XOR of 1010 and 1101 gives 0111 which is 7.
Input : a = 7, b = 5
Output : 2
Explanation : Since the length of binary representations
of 7 i.e, 111 and 5 i.e, 101 are same, hence simply
print XOR of a and b.
Approach : Count the number of bits in binary representation of smaller number out of a
and b. If the number of bits in smaller number(say a) exceeds to that of larger number(say
b), then apply left shift to the smaller number by the number of exceeding bits, i.e, a =
a<<(exceeding bits). After applying left shift, trailing zeroes will be added at the end of
2127
Chapter 348. XOR of two numbers after making length of their binary representations
equal
binary representation of smaller number to make the number of bits in binary representation
of both the numbers equal. XOR both the binary representations to get the final result.
Below is the implementation of above method :
C++
2128
Chapter 348. XOR of two numbers after making length of their binary representations
equal
return (c^d);
}
// driver code to check the above function
int main()
{
int a = 13, b = 5;
cout << XOR(a,b);
return 0;
}
Java
2129
Chapter 348. XOR of two numbers after making length of their binary representations
equal
Python3
2130
Chapter 348. XOR of two numbers after making length of their binary representations
equal
# stores the minimum and maximum
c = min(a, b)
d = max(a, b)
# left shift if the number of bits
# are less in binary representation
if (count(c) < count(d)) :
c = c << ( count(d) - count(c) )
return (c^d)
# Driver Code
a = 13; b = 5
print(XOR(a, b))
# This code is contributed by Nikita Tiwari.
C#
2131
Chapter 348. XOR of two numbers after making length of their binary representations
equal
return c;
}
// function to calculate the xor of
// two numbers by adding trailing
// zeros to the number having less number
// of bits in its binary representation.
static int XOR(int a, int b)
{
// stores the minimum and maximum
int c = Math.Min(a, b);
int d = Math.Max(a, b);
// left shift if the number of bits
// are less in binary representation
if (count(c) < count(d))
c = c << ( count(d) - count(c) );
return (c ^ d);
}
// driver code to check the above function
public static void Main()
{
int a = 13, b = 5;
Console.WriteLine(XOR(a, b));
}
}
// This code is contributed by vt_m.
PHP
<?php
// php implementation to return XOR
// of two numbers after making
// length of their binary
// representation same
// function to count the number
// of bits in binary representation
// of an integer
function count1($n)
{
// initialize count
2132
Chapter 348. XOR of two numbers after making length of their binary representations
equal
$c = 0;
// count till n is
// non zero
while ($n)
{
$c++;
// right shift by 1
// i.e, divide by 2
$n = $n>>1;
}
return $c;
}
// function to calculate the xor of
// two numbers by adding trailing
// zeros to the number having less number
// of bits in its binary representation.
function XOR1($a, $b)
{
// stores the minimum
// and maximum
$c = min($a,$b);
$d = max($a,$b);
// left shift if the number of bits
// are less in binary representation
if (count1($c) < count1($d))
$c = $c << ( count1($d) - count1($c) );
return ($c^$d);
}
// Driver Code
$a = 13;
$b = 5;
echo XOR1($a, $b);
// This code is contributed by mits
?>
Output :
2133
Chapter 348. XOR of two numbers after making length of their binary representations
equal
Source
https://www.geeksforgeeks.org/xor-two-numbers-making-length-binary-representations-equal/
2134
Chapter 349
The image above is the Calkin-Wilf Tree where all the rational numbers are listed. The
children of a node a/b is calculated as a/(a+b) and (a+b)/b.
The task is to find the nth rational number in breadth first traversal of this tree.
Examples:
Input : 13
Output : [5, 3]
2135
Chapter 349. nth Rational number in Calkin-Wilf sequence
Input : 5
Output : [3, 2]
Explanation: This tree is a Perfect Binary Search tree and we need floor(log(n)) steps to
compute nth rational number. The concept is similar to searching in a binary search tree.
Given n we keep dividing it by 2 until we get 0. We return fraction at each stage in the
following manner:-
if n%2 == 0
update frac[1]+=frac[0]
else
update frac[0]+=frac[1]
Below is the program to find the nth number in Calkin Wilf sequence:
C++
2136
Chapter 349. nth Rational number in Calkin-Wilf sequence
nthRational(n);
cout << "[" << frac[0] << ","
<< frac[1] << "]" << endl;
return 0;
}
// This code is contributed
// by Harshit Saini
Java
Python3
2137
Chapter 349. nth Rational number in Calkin-Wilf sequence
frac = [0, 1]
# returns 1x2 int array
# which contains the nth
# rational number
def nthRational(n):
if n > 0:
nthRational(int(n / 2))
# ~n&1 is equivalent to
# !n%2?1:0 and n&1 is
# equivalent to n%2
frac[~n & 1] += frac[n & 1]
return frac
# Driver code
if __name__ == "__main__":
n = 13 # testing for n=13
# converting array
# to string format
print(nthRational(n))
# This code is contributed
# by Harshit Saini
Output:
[5, 3]
Explanation:
For n = 13,
2138
Chapter 349. nth Rational number in Calkin-Wilf sequence
Source
https://www.geeksforgeeks.org/nth-rational-number-in-calkin-wilf-sequence/
2139