Given a binary number as a string s consisting of characters ('0' and '1'). Your task is to find if this binary number is divisible by 3.
Note:Â Try to accomplish this using a single traversal of the input binary string.
Examples:
Input: s = "100"
Output: false
Explanation: "100"'s decimal equivalent is 4, which is not divisible by 3.Input: s = "0011"
Output: true
Explanation: "0011" is 3, which is divisible by 3.Input: s = "110"
Output: true
Explanation: The decimal equivalent of "110" is6, which is divisible by 3.
Table of Content
Brute Force - O(n) Time and O(1) Space
The idea is to convert the binary string into its decimal equivalent. We can traverse the string from left to right and repeatedly multiply the current value by
2and add the current bit. Once the complete decimal number is obtained, we simply check whether it is divisible by3.
Problems with this approach: The constraint allows the binary string to have up to 10^6 bits. A standard integer type such as long long can store only around 64 bits. Therefore, for a binary string containing millions of bits, the decimal value will be far beyond the range of long long, resulting in integer overflow. Hence, this approach is not suitable for the given constraints.
Running Remainder - O(n) Time and O(1) Space
The idea is to traverse the string from left to right and maintain the remainder when the number formed so far is divided by 3. When a new binary digit is appended, the new number becomes oldNumber * 2 + bit, so we update the remainder using the same formula modulo 3.
At the end, if the remainder is 0, the binary number is divisible by 3.
- Initialize rem = 0.
- Traverse the binary string from left to right.
- Convert the current character into its binary digit using s[i] - '0'.
- Update the remainder using rem = (rem * 2 + bit) % 3.
- Continue this for every character in the string.
- Return true if the final remainder is 0; otherwise return false.
#include <bits/stdc++.h>
using namespace std;
bool isMultipleOf3(string &s)
{
int rem = 0;
// Traverse the binary string from left to right
for (char ch : s)
{
// Convert the current character into a binary digit
int bit = ch - '0';
// Append the current bit to the number.
// We only keep the remainder modulo 3
// to avoid constructing the complete decimal number.
rem = (rem * 2 + bit) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem == 0;
}
int main()
{
string s = "110";
cout << (isMultipleOf3(s) ? "true" : "false");
return 0;
}
import java.util.*;
class GFG {
static boolean isMultipleOf3(String s)
{
int rem = 0;
// Traverse the binary string from left to right
for (char ch : s.toCharArray()) {
// Convert the current character into a binary
// digit
int bit = ch - '0';
// Append the current bit to the number.
// We only keep the remainder modulo 3
// to avoid constructing the complete decimal
// number.
rem = (rem * 2 + bit) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem == 0;
}
public static void main(String[] args)
{
String s = "110";
System.out.println(isMultipleOf3(s) ? "true"
: "false");
}
}
def isMultipleOf3(s):
rem = 0
# Traverse the binary string from left to right
for ch in s:
# Convert the current character into a binary digit
bit = ord(ch) - ord('0')
# Append the current bit to the number.
# We only keep the remainder modulo 3
# to avoid constructing the complete decimal number.
rem = (rem * 2 + bit) % 3
# If the final remainder is 0,
# the binary number is divisible by 3.
return rem == 0
# Driver Code
if __name__ == "__main__":
s = "110"
print("true" if isMultipleOf3(s) else "false")
using System;
class GFG {
static bool isMultipleOf3(string s)
{
int rem = 0;
// Traverse the binary string from left to right
foreach(char ch in s)
{
// Convert the current character into a binary
// digit
int bit = ch - '0';
// Append the current bit to the number.
// We only keep the remainder modulo 3
// to avoid constructing the complete decimal
// number.
rem = (rem * 2 + bit) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem == 0;
}
static void Main()
{
string s = "110";
Console.WriteLine(isMultipleOf3(s) ? "true"
: "false");
}
}
function isMultipleOf3(s)
{
let rem = 0;
// Traverse the binary string from left to right
for (let ch of s) {
// Convert the current character into a binary digit
let bit = ch.charCodeAt(0) - "0".charCodeAt(0);
// Append the current bit to the number.
// We only keep the remainder modulo 3
// to avoid constructing the complete decimal
// number.
rem = (rem * 2 + bit) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem === 0;
}
// Driver Code
let s = "110";
console.log(isMultipleOf3(s) ? "true" : "false");
Output
true
Sum of Powers of 2 Modulo 3 - O(n) Time and O(1) Space
Each 1 in binary representation contributes a power of 2 based on its position. Since we only need divisibility by 3, we calculate each power of 2 modulo 3.
Starting from the rightmost bit, maintain x = 2^i % 3 and add it to the answer whenever the current bit is 1. If the final sum modulo 3 is 0, the binary number is divisible by 3.
- Initialize rem = 0 and x = 1, where x represents the current power of 2 modulo 3.
- Traverse the binary string from right to left.
- If the current bit is 1, add its contribution x to rem and take modulo 3.
- Update the next power using x = (x * 2) % 3.
- Continue until all bits have been processed.
- Return true if rem == 0; otherwise return false.
#include <bits/stdc++.h>
using namespace std;
bool isMultipleOf3(string &s)
{
int rem = 0;
int x = 1;
// Traverse the binary string from right to left
for (int i = s.length() - 1; i >= 0; i--)
{
// If the current bit is 1,
// add its contribution to the remainder.
if (s[i] - '0' == 1)
{
rem = (rem + x) % 3;
}
// Update the power of 2 modulo 3
x = (x * 2) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem == 0;
}
int main()
{
string s = "110";
cout << (isMultipleOf3(s) ? "true" : "false");
return 0;
}
import java.util.*;
class GFG {
static boolean isMultipleOf3(String s)
{
int rem = 0;
int x = 1;
// Traverse the binary string from right to left
for (int i = s.length() - 1; i >= 0; i--) {
// If the current bit is 1,
// add its contribution to the remainder.
if (s.charAt(i) - '0' == 1) {
rem = (rem + x) % 3;
}
// Update the power of 2 modulo 3
x = (x * 2) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem == 0;
}
public static void main(String[] args)
{
String s = "110";
System.out.println(isMultipleOf3(s) ? "true"
: "false");
}
}
def isMultipleOf3(s):
rem = 0
x = 1
# Traverse the binary string from right to left
for i in range(len(s) - 1, -1, -1):
# If the current bit is 1,
# add its contribution to the remainder.
if ord(s[i]) - ord('0') == 1:
rem = (rem + x) % 3
# Update the power of 2 modulo 3
x = (x * 2) % 3
# If the final remainder is 0,
# the binary number is divisible by 3.
return rem == 0
# Driver Code
if __name__ == "__main__":
s = "110"
print("true" if isMultipleOf3(s) else "false")
using System;
class GFG {
static bool isMultipleOf3(string s)
{
int rem = 0;
int x = 1;
// Traverse the binary string from right to left
for (int i = s.Length - 1; i >= 0; i--) {
// If the current bit is 1,
// add its contribution to the remainder.
if (s[i] - '0' == 1) {
rem = (rem + x) % 3;
}
// Update the power of 2 modulo 3
x = (x * 2) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem == 0;
}
static void Main()
{
string s = "110";
Console.WriteLine(isMultipleOf3(s) ? "true"
: "false");
}
}
function isMultipleOf3(s)
{
let rem = 0;
let x = 1;
// Traverse the binary string from right to left
for (let i = s.length - 1; i >= 0; i--) {
// If the current bit is 1,
// add its contribution to the remainder.
if (s.charCodeAt(i) - "0".charCodeAt(0) === 1) {
rem = (rem + x) % 3;
}
// Update the power of 2 modulo 3
x = (x * 2) % 3;
}
// If the final remainder is 0,
// the binary number is divisible by 3.
return rem === 0;
}
// Driver Code
let s = "110";
console.log(isMultipleOf3(s) ? "true" : "false");
Output
true