Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Count of subsequences of length 4 in form (x, x, x+1, x+1) | Set 2
Next article icon

Count Subsequence of 101 in binary form of a number

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number N, the task is to count the occurrences of 101 subsequences in the binary representation of that number.

Examples:

Input: N = 10
Output: 1
Explanation: The binary representation of the number 10 is 1010 and there is only one subsequence 101 which is starting from the left end of binary form is present.

Input: N = 21
Output: 4
Explanation: The binary representation of 21 is 10101 and there are total 4 subsequences of 101 are present.

Approach: To solve the problem follow the below observations:

Observations:

The key to this problem is observations. So if we have binary representation like 101, then the total contribution of a zero is multiplication of the number of 1's present at its left and number of 1's present at its right.

Illustration:

For example, 21 whose binary is 10101 if we talk about 0 present at index-1 there is one 1 at its left and two 1 at right so it can contribute total 1*2=2, and for another 0 present at index-3 there is two 1 at left and one 1 at right so it will contribute 2*1=2. So the answer will be 2+2 = 4.

Steps to implement the above approach:

  • Call the totalCount function to return the count of 101 subsequences.
  • Iterate over each bit in n
    • First, for every 0 bit, we push the number of 1s to its right in the right vector. Also, simultaneously increase the count of the number of 1 bit.
  • Iterate over this vector, and update the ans with the multiplication of the number of 1s on left and right respectively for every 0.

Below is the code to implement the above steps:

C++
#include <bits/stdc++.h> using namespace std; long long TotalCount(long long n) {      // To keep number of 1 at right     vector<int> right;      // Total answer     long long ans = 0;      // Total 1     int one = 0;      while (n != 0) {          // If bit is set         if (n & 1) {             one++;         }          // Else the total number of one         // till now is right for current 0         else {             right.push_back(one);         }          n >>= 1;     }      for (auto x : right) {          // Number of one's at left =         // total-right         int left = one - x;          // Adding to answer the         // contribution of current 0         ans += (left * x);     }      return ans; }  // Drivers code int main() {      // Given number     long long n = 21;      // Calling function     cout << TotalCount(n) << endl;      return 0; } 
Java
import java.util.*;  public class Main {     public static long TotalCount(long n)     {          // To keep number of 1 at right         List<Integer> right = new ArrayList<>();          // Total answer         long ans = 0;          // Total 1         int one = 0;          while (n != 0) {              // If bit is set             if ((n & 1) == 1) {                 one++;             }              // Else the total number of one             // till now is right for current 0             else {                 right.add(one);             }              n >>= 1;         }          for (int x : right) {              // Number of one's at left =             // total-right             int left = one - x;              // Adding to answer the             // contribution of current 0             ans += (left * x);         }          return ans;     }      // Drivers code     public static void main(String[] args)     {          // Given number         long n = 21;          // Calling function         System.out.println(TotalCount(n));     } } // This code is contributed by Prajwal Kandekar 
Python3
def total_count(n):     # To keep number of 1 at right     right = []      # Total answer     ans = 0      # Total 1     one = 0      while n != 0:         # If bit is set         if n & 1:             one += 1         # Else the total number of one         # till now is right for current 0         else:             right.append(one)         n >>= 1      for x in right:         # Number of one's at left =         # total-right         left = one - x          # Adding to answer the         # contribution of current 0         ans += left * x      return ans  # Driver code if __name__ == "__main__":     # Given number     n = 21      # Calling function     print(total_count(n)) 
C#
using System; using System.Collections.Generic;  public class GFG{        public static long TotalCount(long n)     {          // To keep number of 1 at right         List<int> right = new List<int>();          // Total answer         long ans = 0;          // Total 1         int one = 0;          while (n != 0) {              // If bit is set             if ((n & 1) == 1) {                 one++;             }              // Else the total number of one             // till now is right for current 0             else {                 right.Add(one);             }              n >>= 1;         }          foreach (int x in right) {              // Number of one's at left =             // total-right             int left = one - x;              // Adding to answer the             // contribution of current 0             ans += (left * x);         }          return ans;     }      // Drivers code     public static void Main(String[] args)     {          // Given number         long n = 21;          // Calling function         Console.WriteLine(TotalCount(n));     } } 
JavaScript
function TotalCount(n) { //To keep number of 1 at right let right = []; //Total answer let ans = 0; //To keep number of 1 at right let one = 0;  while (n != 0) {     if (n & 1) {         one++;     }     else {         right.push(one);     }      n >>= 1; }  for (let x of right) {     let left = one - x;     ans += (left * x); }  return ans; }  // Given number let n = 21; // Calling function console.log(TotalCount(n)); 

Output
4

Time Complexity: O(Log(N))
Auxiliary Space: O(Log(N))


Next Article
Count of subsequences of length 4 in form (x, x, x+1, x+1) | Set 2
author
shubhamrajput6156
Improve
Article Tags :
  • Bit Magic
  • DSA
Practice Tags :
  • Bit Magic

Similar Reads

  • Count of subsequences of length 4 in form (x, x, x+1, x+1) | Set 2
    Given a large number in form of string str of size N, the task is to count the subsequence of length 4 whose digit are in the form of (x, x, x+1, x+1).Example: Input: str = "1515732322" Output: 3 Explanation: For the given input string str = "1515732322", there are 3 subsequence {1122}, {1122}, and
    10 min read
  • Count of unique subsequences from given number which are power of 2
    Given a string S of size N and containing digits in the range [0-9], the task is to print the count of all the unique subsequences of a string that are the power of 2. Examples: Input: S = "1216389"Output: 5Explanation:All the possible unique subsequences that are power of 2 are: {1, 2, 16, 128, 8}
    8 min read
  • Maximum count of “010..” subsequences that can be removed from given Binary String
    Given a binary string S consisting of size N, the task is to find the maximum number of binary subsequences of the form "010.." of length at least 2 that can be removed from the given string S. Examples: Input: S = "110011010"Output: 3Explanation:Following are the subsequence removed:Operation 1: Ch
    6 min read
  • Minimize deletions in a Binary String to remove all subsequences of the form "0101"
    Given a binary string S of length N, the task is to find the minimum number of characters required to be deleted from the string such that no subsequence of the form “0101” exists in the string. Examples: Input: S = "0101101"Output: 2Explanation: Removing S[1] and S[5] modifies the string to 00111.
    6 min read
  • Generate Binary String with equal number of 01 and 10 Subsequence
    Given an integer N (N > 2), the task is to generate a binary string of size N that consists of equal numbers of "10" & "01" subsequences and also the string should contain at least one '0' and one '1' Note: If multiple such strings exist, print any. Examples: Input: 4Output: 0110Explanation :
    7 min read
  • Number of subsequences in a given binary string divisible by 2
    Given binary string str of length N, the task is to find the count of subsequences of str which are divisible by 2. Leading zeros in a sub-sequence are allowed. Examples: Input: str = "101" Output: 2 "0" and "10" are the only subsequences which are divisible by 2.Input: str = "10010" Output: 22 Naiv
    4 min read
  • Sum of all subsequences of a number
    Given a number as string s, find the sum of all the elements present in all possible subsequences of s.Examples : Input : s = "123" Output : 24 Explanation : all possible sub-sequences are 1, 2, 3, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3} which add up to 24 Input : s = "453" Output : 48 Recommended Practic
    14 min read
  • Count total unset bits in all the numbers from 1 to N
    Given a positive integer N, the task is to count the total number of unset bits in the binary representation of all the numbers from 1 to N. Note that leading zeroes will not be counted as unset bits.Examples: Input: N = 5 Output: 4 IntegerBinary RepresentationCount of unset bits11021013110410025101
    4 min read
  • Longest subsequence having equal numbers of 0 and 1
    Given a binary array, the task is to find the size of the largest sub_sequence which having equal number of zeros and one. Examples : Input : arr[] = { 1, 0, 0, 1, 0, 0, 0, 1 } Output: 6 Input : arr[] = { 0, 0, 1, 1, 1, 1, 1, 0, 0 }Output : 8 simple solution is that we generate all possible sub_sequ
    11 min read
  • Count number of binary strings of length N having only 0's and 1's
    Given an integer N, the task is to count the number of binary strings of length N having only 0's and 1's. Note: Since the count can be very large, return the answer modulo 10^9+7. Examples: Input: 2 Output: 4 Explanation: The numbers are 00, 01, 11, 10. Hence the count is 4. Input: 3 Output: 8 Expl
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences