Check if decimal representation of Binary String is divisible by 9 or not
Last Updated :
23 Jul, 2025
Given a binary string S of length N, the task is to check if the decimal representation of the binary string is divisible by 9 or not.
Examples:
Input: S = 1010001
Output:Yes
Explanation: The decimal representation of the binary string S is 81, which is divisible by 9. Therefore, the required output is Yes.
Input: S = 1010011
Output: No
Explanation: The decimal representation of the binary string S is 83, which is not divisible by 9. Therefore, the required output is No.
Naive Approach: The simplest approach to solve this problem is to convert the binary number into a decimal number and check if the decimal number is divisible by 9 or not. If found to be true then print True. Otherwise, print False.
C++
#include<iostream>
#include<bitset>
using namespace std;
void is_binary_divisible_by_9(string s){
bitset<32> decimal_num(s);
if(decimal_num.to_ulong() % 9 == 0){
cout << "Yes\n";
} else {
cout << "No\n";
}
}
// Example Usage
int main() {
string s = "1010001";
is_binary_divisible_by_9(s);
return 0;
}
Java
public class BinaryDivisibleByNine {
// Function to check if binary string
// is divisible by 9 or not
public static String isBinaryDivisibleByNine(String s) {
// Convert the binary string to its decimal representation
int decimal_num = Integer.parseInt(s, 2);
// Check if the decimal representation is divisible by 9
if (decimal_num % 9 == 0) {
return "Yes";
} else {
return "No";
}
}
public static void main(String[] args) {
String s = "1010001";
System.out.println(isBinaryDivisibleByNine(s));
}
}
Python3
def is_binary_divisible_by_9(s):
decimal_num = int(s, 2)
if decimal_num % 9 == 0:
print("Yes")
else:
print("No")
# Example Usage
s = '1010001'
is_binary_divisible_by_9(s)
C#
using System;
public class BinaryDivisibleByNine {
// Function to check if binary string is divisible by 9
// or not
public static string IsBinaryDivisibleByNine(string s)
{
// Convert the binary string to its decimal
// representation
int decimal_num = Convert.ToInt32(s, 2);
// Check if the decimal representation is divisible
// by 9
if (decimal_num % 9 == 0) {
return "Yes";
}
else {
return "No";
}
}
public static void Main(string[] args)
{
string s = "1010001";
Console.WriteLine(IsBinaryDivisibleByNine(s));
}
}
JavaScript
function isBinaryDivisibleByNine(s) {
// Convert the binary string to its decimal representation
let decimal_num = parseInt(s, 2);
// Check if the decimal representation is divisible by 9
if (decimal_num % 9 === 0) {
return "Yes";
} else {
return "No";
}
}
let s = "1010001";
console.log(isBinaryDivisibleByNine(s));
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: If the length of a binary string is greater than 64 then the decimal representation of the binary string will cause an overflow. Therefore, to reduce the overflow issue the idea is to convert the binary string into the octal representation and check if the octal representation of the binary string is divisible by 9 or not. Follow the steps below to solve the problem:
- Convert the binary string into octal representation.
- Initialize a variable, say Oct_9 to store the octal representation of 9.
- Find the sum of digits, say evenSum present at even positions in the octal representation of the binary string.
- Find the sum of digits, say oddSum present at odd positions in the octal representation of the binary string.
- Check if abs(oddSum - EvenSum) % Oct_9 == 0 or not. If found to be true, then print Yes.
- Otherwise, print No.
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to convert the binary string
// into octal representation
string ConvertequivalentBase8(string S)
{
// Stores binary representation of
// the decimal value [0 - 7]
map<string, char> mp;
// Stores the decimal values
// of binary strings [0 - 7]
mp["000"] = '0';
mp["001"] = '1';
mp["010"] = '2';
mp["011"] = '3';
mp["100"] = '4';
mp["101"] = '5';
mp["110"] = '6';
mp["111"] = '7';
// Stores length of S
int N = S.length();
if (N % 3 == 2) {
// Update S
S = "0" + S;
}
else if (N % 3 == 1) {
// Update S
S = "00" + S;
}
// Update N
N = S.length();
// Stores octal representation
// of the binary string
string oct;
// Traverse the binary string
for (int i = 0; i < N; i += 3) {
// Stores 3 consecutive characters
// of the binary string
string temp = S.substr(i, 3);
// Append octal representation
// of temp
oct.push_back(mp[temp]);
}
return oct;
}
// Function to check if binary string
// is divisible by 9 or not
string binString_div_9(string S, int N)
{
// Stores octal representation
// of S
string oct;
oct = ConvertequivalentBase8(S);
// Stores sum of elements present
// at odd positions of oct
int oddSum = 0;
// Stores sum of elements present
// at odd positions of oct
int evenSum = 0;
// Stores length of oct
int M = oct.length();
// Traverse the string oct
for (int i = 0; i < M; i += 2) {
// Update oddSum
oddSum += int(oct[i] - '0');
}
// Traverse the string oct
for (int i = 1; i < M; i += 2) {
// Update evenSum
evenSum += int(oct[i] - '0');
}
// Stores cotal representation
// of 9
int Oct_9 = 11;
// If absolute value of (oddSum
// - evenSum) is divisible by Oct_9
if (abs(oddSum - evenSum) % Oct_9
== 0) {
return "Yes";
}
return "No";
}
// Driver Code
int main()
{
string S = "1010001";
int N = S.length();
cout << binString_div_9(S, N);
}
Java
// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
// Function to convert the binary string
// into octal representation
static String ConvertequivalentBase8(String S)
{
// Stores binary representation of
// the decimal value [0 - 7]
HashMap<String,
Character> mp = new HashMap<String,
Character>();
// Stores the decimal values
// of binary Strings [0 - 7]
mp.put("000", '0');
mp.put("001", '1');
mp.put("010", '2');
mp.put("011", '3');
mp.put("100", '4');
mp.put("101", '5');
mp.put("110", '6');
mp.put("111", '7');
// Stores length of S
int N = S.length();
if (N % 3 == 2)
{
// Update S
S = "0" + S;
}
else if (N % 3 == 1)
{
// Update S
S = "00" + S;
}
// Update N
N = S.length();
// Stores octal representation
// of the binary String
String oct = "";
// Traverse the binary String
for(int i = 0; i < N; i += 3)
{
// Stores 3 consecutive characters
// of the binary String
String temp = S.substring(i, i + 3);
// Append octal representation
// of temp
oct += mp.get(temp);
}
return oct;
}
// Function to check if binary String
// is divisible by 9 or not
static String binString_div_9(String S, int N)
{
// Stores octal representation
// of S
String oct = "";
oct = ConvertequivalentBase8(S);
// Stores sum of elements present
// at odd positions of oct
int oddSum = 0;
// Stores sum of elements present
// at odd positions of oct
int evenSum = 0;
// Stores length of oct
int M = oct.length();
// Traverse the String oct
for(int i = 0; i < M; i += 2)
// Update oddSum
oddSum += (oct.charAt(i) - '0');
// Traverse the String oct
for(int i = 1; i < M; i += 2)
{
// Update evenSum
evenSum += (oct.charAt(i) - '0');
}
// Stores octal representation
// of 9
int Oct_9 = 11;
// If absolute value of (oddSum
// - evenSum) is divisible by Oct_9
if (Math.abs(oddSum - evenSum) % Oct_9 == 0)
{
return "Yes";
}
return "No";
}
// Driver Code
public static void main(String[] args)
{
String S = "1010001";
int N = S.length();
System.out.println(binString_div_9(S, N));
}
}
// This code is contributed by grand_master
Python3
# Python3 program to implement
# the above approach
# Function to convert the binary
# string into octal representation
def ConvertequivalentBase8(S):
# Stores binary representation of
# the decimal value [0 - 7]
mp = {}
# Stores the decimal values
# of binary strings [0 - 7]
mp["000"] = '0'
mp["001"] = '1'
mp["010"] = '2'
mp["011"] = '3'
mp["100"] = '4'
mp["101"] = '5'
mp["110"] = '6'
mp["111"] = '7'
# Stores length of S
N = len(S)
if (N % 3 == 2):
# Update S
S = "0" + S
elif (N % 3 == 1):
# Update S
S = "00" + S
# Update N
N = len(S)
# Stores octal representation
# of the binary string
octal = ""
# Traverse the binary string
for i in range(0, N, 3):
# Stores 3 consecutive characters
# of the binary string
temp = S[i: i + 3]
# Append octal representation
# of temp
if temp in mp:
octal += (mp[temp])
return octal
# Function to check if binary string
# is divisible by 9 or not
def binString_div_9(S, N):
# Stores octal representation
# of S
octal = ConvertequivalentBase8(S)
# Stores sum of elements present
# at odd positions of oct
oddSum = 0
# Stores sum of elements present
# at odd positions of oct
evenSum = 0
# Stores length of oct
M = len(octal)
# Traverse the string oct
for i in range(0, M, 2):
# Update oddSum
oddSum += ord(octal[i]) - ord('0')
# Traverse the string oct
for i in range(1, M, 2):
# Update evenSum
evenSum += ord(octal[i]) - ord('0')
# Stores cotal representation
# of 9
Oct_9 = 11
# If absolute value of (oddSum
# - evenSum) is divisible by Oct_9
if (abs(oddSum - evenSum) % Oct_9 == 0):
return "Yes"
return "No"
# Driver Code
if __name__ == "__main__":
S = "1010001"
N = len(S)
print(binString_div_9(S, N))
# This code is contributed by chitranayal
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to convert the binary string
// into octal representation
static String ConvertequivalentBase8(String S)
{
// Stores binary representation of
// the decimal value [0 - 7]
Dictionary<String,
char> mp = new Dictionary<String,
char>();
// Stores the decimal values
// of binary Strings [0 - 7]
mp.Add("000", '0');
mp.Add("001", '1');
mp.Add("010", '2');
mp.Add("011", '3');
mp.Add("100", '4');
mp.Add("101", '5');
mp.Add("110", '6');
mp.Add("111", '7');
// Stores length of S
int N = S.Length;
if (N % 3 == 2)
{
// Update S
S = "0" + S;
}
else if (N % 3 == 1)
{
// Update S
S = "00" + S;
}
// Update N
N = S.Length;
// Stores octal representation
// of the binary String
String oct = "";
// Traverse the binary String
for(int i = 0; i < N; i += 3)
{
// Stores 3 consecutive characters
// of the binary String
String temp = S.Substring(0, N);
// Append octal representation
// of temp
if (mp.ContainsKey(temp))
oct += mp[temp];
}
return oct;
}
// Function to check if binary String
// is divisible by 9 or not
static String binString_div_9(String S, int N)
{
// Stores octal representation
// of S
String oct = "";
oct = ConvertequivalentBase8(S);
// Stores sum of elements present
// at odd positions of oct
int oddSum = 0;
// Stores sum of elements present
// at odd positions of oct
int evenSum = 0;
// Stores length of oct
int M = oct.Length;
// Traverse the String oct
for(int i = 0; i < M; i += 2)
// Update oddSum
oddSum += (oct[i] - '0');
// Traverse the String oct
for(int i = 1; i < M; i += 2)
{
// Update evenSum
evenSum += (oct[i] - '0');
}
// Stores octal representation
// of 9
int Oct_9 = 11;
// If absolute value of (oddSum
// - evenSum) is divisible by Oct_9
if (Math.Abs(oddSum - evenSum) % Oct_9 == 0)
{
return "Yes";
}
return "No";
}
// Driver Code
public static void Main(String[] args)
{
String S = "1010001";
int N = S.Length;
Console.WriteLine(binString_div_9(S, N));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to convert the binary string
// into octal representation
function ConvertequivalentBase8(S)
{
// Stores binary representation of
// the decimal value [0 - 7]
let mp = new Map();
// Stores the decimal values
// of binary Strings [0 - 7]
mp.set("000", '0');
mp.set("001", '1');
mp.set("010", '2');
mp.set("011", '3');
mp.set("100", '4');
mp.set("101", '5');
mp.set("110", '6');
mp.set("111", '7');
// Stores length of S
let N = S.length;
if (N % 3 == 2)
{
// Update S
S = "0" + S;
}
else if (N % 3 == 1)
{
// Update S
S = "00" + S;
}
// Update N
N = S.length;
// Stores octal representation
// of the binary String
let oct = "";
// Traverse the binary String
for(let i = 0; i < N; i += 3)
{
// Stores 3 consecutive characters
// of the binary String
let temp = S.substring(i, i + 3);
// Append octal representation
// of temp
oct += mp.get(temp);
}
return oct;
}
// Function to check if binary String
// is divisible by 9 or not
function binString_div_9(S, N)
{
// Stores octal representation
// of S
let oct = "";
oct = ConvertequivalentBase8(S);
// Stores sum of elements present
// at odd positions of oct
let oddSum = 0;
// Stores sum of elements present
// at odd positions of oct
let evenSum = 0;
// Stores length of oct
let M = oct.length;
// Traverse the String oct
for(let i = 0; i < M; i += 2)
// Update oddSum
oddSum += (oct[i] - '0');
// Traverse the String oct
for(let i = 1; i < M; i += 2)
{
// Update evenSum
evenSum += (oct[i] - '0');
}
// Stores octal representation
// of 9
let Oct_9 = 11;
// If absolute value of (oddSum
// - evenSum) is divisible by Oct_9
if (Math.abs(oddSum - evenSum) % Oct_9 == 0)
{
return "Yes";
}
return "No";
}
// Driver Code
let S = "1010001";
let N = S.length;
document.write(binString_div_9(S, N));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
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