Check if bits of a number has count of consecutive set bits in increasing order
Last Updated :
11 Sep, 2023
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++
// C++ program to find if bit-pattern
// of a number has increasing value of
// continuous-1 or not.
#include <bits/stdc++.h>
using namespace std;
// Returns true if n has increasing count of
// continuous-1 else false
bool findContinuous1(int n)
{
const int bits = 8 * sizeof(int);
// store the bit-pattern of n into
// bit bitset- bp
string bp = bitset<bits>(n).to_string();
// set prev_count = 0 and curr_count = 0.
int prev_count = 0, curr_count = 0;
int i = 0;
while (i < bits) {
if (bp[i] == '1') {
// increment current count of continuous-1
curr_count++;
i++;
}
// traverse all continuous-0
else if (bp[i - 1] == '0') {
i++;
curr_count = 0;
continue;
}
// check prev_count and curr_count
// on encounter of first zero after
// continuous-1s
else {
if (curr_count < prev_count)
return 0;
i++;
prev_count = curr_count;
curr_count = 0;
}
}
// 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;
}
Java
// Java program to find if bit-pattern
// of a number has increasing value of
// continuous-1 or not.
import java.io.*;
public class GFG {
// Returns true if n has increasing count of
// continuous-1 else false
static boolean findContinuous1(int n)
{
// converting decimal integer to binary string then
// store the bit-pattern of n into
// bit bitset- bp by converting the binary string to
// char array
char[] bp
= (Integer.toBinaryString(n)).toCharArray();
int bits = bp.length;
// set prev_count = 0 and curr_count = 0.
int prev_count = 0;
int curr_count = 0;
int i = 0;
while (i < bits) {
if (bp[i] == '1')
{
// increment current count of continuous-1
curr_count++;
i++;
}
// traverse all continuous-0
else if (bp[i - 1] == '0') {
i++;
curr_count = 0;
continue;
}
// check prev_count and curr_count
// on encounter of first zero after
// continuous-1s
else {
if (curr_count < prev_count)
return false;
i++;
prev_count = curr_count;
curr_count = 0;
}
}
// check for last sequence of continuous-1
if ((prev_count > curr_count) && (curr_count != 0))
return false;
return true;
}
// Driver code
public static void main(String args[])
{
int n = 179;
if (findContinuous1(n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by phasing17
Python3
# Python3 program to find if bit-pattern
# of a number has increasing value of
# continuous-1 or not.
# Returns true if n has increasing count of
# continuous-1 else false
def findContinuous1(n):
# store the bit-pattern of n into
# bit bitset- bp
bp = list(bin(n))
bits = len(bp)
# set prev_count = 0 and curr_count = 0.
prev_count = 0
curr_count = 0
i = 0
while (i < bits):
if (bp[i] == '1'):
# increment current count of continuous-1
curr_count += 1
i += 1
# traverse all continuous-0
elif (bp[i - 1] == '0'):
i += 1
curr_count = 0
continue
# check prev_count and curr_count
# on encounter of first zero after
# continuous-1s
else:
if (curr_count < prev_count):
return 0
i += 1
prev_count = curr_count
curr_count = 0
# check for last sequence of continuous-1
if (prev_count > curr_count and (curr_count != 0)):
return 0
return 1
# Driver code
n = 179
if (findContinuous1(n)):
print("Yes")
else:
print("No")
# This code is contributed by SHUBHAMSINGH10
C#
// C# program to find if bit-pattern
// of a number has increasing value of
// continuous-1 or not.
using System;
using System.Collections.Specialized;
class GFG
{
// Returns true if n has increasing count of
// continuous-1 else false
static bool findContinuous1(int n)
{
// store the bit-pattern of n into
// bit bitset- bp
string bp = Convert.ToString(n, 2);
int bits = bp.Length;
// set prev_count = 0 and curr_count = 0.
int prev_count = 0, curr_count = 0;
int i = 0;
while (i < bits)
{
if (bp[i] == '1')
{
// increment current count of continuous-1
curr_count++;
i++;
}
// traverse all continuous-0
else if (bp[i - 1] == '0') {
i++;
curr_count = 0;
continue;
}
// check prev_count and curr_count
// on encounter of first zero after
// continuous-1s
else {
if (curr_count < prev_count)
return false;
i++;
prev_count = curr_count;
curr_count = 0;
}
}
// check for last sequence of continuous-1
if (prev_count > curr_count && (curr_count != 0))
return false;
return true;
}
// Driver Code
static void Main()
{
int n = 179;
if (findContinuous1(n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This Code was contributed by phasing17
JavaScript
<script>
// JavaScript program to find if bit-pattern
// of a number has increasing value of
// continuous-1 or not.
function dec2bin(dec) {
return (dec >>> 0).toString(2);
}
// Returns true if n has increasing count of
// continuous-1 else false
function findContinuous1(n){
// store the bit-pattern of n into
// bit bitset- bp
let bp = dec2bin(n)
let bits = bp.length
// set prev_count = 0 and curr_count = 0.
let prev_count = 0
let curr_count = 0
let i = 0
while (i < bits){
if (bp[i] == '1'){
// increment current count of continuous-1
curr_count += 1;
i += 1;
}
// traverse all continuous-0
else if (bp[i - 1] == '0'){
i += 1
curr_count = 0
continue
}
// check prev_count and curr_count
// on encounter of first zero after
// continuous-1s
else{
if (curr_count < prev_count)
return 0
i += 1
prev_count = curr_count
curr_count = 0
}
}
// check for last sequence of continuous-1
if (prev_count > curr_count && (curr_count != 0))
return 0
return 1
}
// Driver code
n = 179
if (findContinuous1(n))
document.write( "Yes")
else
document.write( "No")
</script>
Time Complexity: O(logn)
Auxiliary Space: O(logn)
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++
// C++ program to check if counts of consecutive
// 1s are increasing order.
#include<bits/stdc++.h>
using namespace std;
// Returns true if n has counts of consecutive
// 1's are increasing order.
bool areSetBitsIncreasing(int n)
{
// Initialize previous count
int prev_count = 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
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
int main()
{
int n = 10;
if (areSetBitsIncreasing(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program to check if counts of
// consecutive 1s are increasing order.
import java .io.*;
class GFG {
// Returns true if n has counts of
// consecutive 1's are increasing
// 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");
}
}
// This code is contributed by anuj_67.
Python3
# Python3 program to check if counts of
# consecutive 1s are increasing order.
import sys
# Returns true if n has counts of
# consecutive 1's are increasing order.
def areSetBitsIncreasing(n):
# Initialize previous count
prev_count = sys.maxsize
# 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 and n % 2 == 0):
n = int(n/2)
# Count current set bits
curr_count = 1
while (n > 0 and n % 2 == 1):
n = n/2
curr_count += 1
# Compare current with previous
# and update previous.
if (curr_count >= prev_count):
return False
prev_count = curr_count
return True
# Driver code
n = 10
if (areSetBitsIncreasing(n)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha
C#
// C# program to check if counts of
// consecutive 1s are increasing order.
using System;
class GFG {
// Returns true if n has counts of
// consecutive 1's are increasing
// order.
static bool areSetBitsIncreasing(int n)
{
// Initialize previous count
int prev_count = int.MaxValue;
// 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 ()
{
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++;
}
// Compare current with previous
// and update previous.
if ($curr_count >= $prev_count)
return false;
$prev_count = $curr_count;
}
return true;
}
// Driver code
$n = 10;
if (areSetBitsIncreasing($n))
echo "Yes";
else
echo "No";
// This code is contributed by anuj_67
?>
JavaScript
<script>
// Javascript 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
var prev_count = Number.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 = parseInt(n / 2);
// Count current set bits
var 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
var n = 10;
if (areSetBitsIncreasing(n))
document.write("Yes");
else
document.write("No");
// This code is contributed by Rajput-Ji
</script>
Time Complexity: O(log2n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem