**Problem Statement:** Convert a binary number to an octal number

**Examples:**

Example 1:.Input:N = 1100110Output:146Explanation:1100110 when converted to octal number is “146”.Example 2:Input:11111Output:37Explanation:11111 when converted to octal number is “37”.

**Solution**

** Disclaimer**:

*Don’t jump directly to the solution, try it out yourself first.*

**Intuition: **Since we have to convert it into an octal number, every bit should be between 0 to 7. We know that every number can be represented by the power of 2. So we will use the 4 2 1 rule, since using 4 2 1 we can make any number between 0 to 7.

**Approach: ** 4 2 1 are 3 digits, so we will divide the string into parts of 3. In the diagram since the length of the string is 7,”00” is added to the left to make the length of the string multiple of 3.

- Let n be length of string.Add appropriate number of “0” at the beginning of string to make the length of string divisible by 3.
- Now transverse from 0 to n.If the ith bit is set add 4,if (i+1)th bit is set add 2 and if (i+2)th bit is set add 1.This will be one bit of the octal number.
- Then increment i by 3,and repeat the 2nd step.

**Code:**

## C++ Code

```
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s = "1100110";
int n = s.length();
if (n % 3 == 1) {
s = "00" + s;
}
else if (n % 3 == 2) {
s = "0" + s;
}
n = s.length();
string ans = "";
for (int i = 0; i < n; i += 3) {
int temp = (s[i] - '0') * 4 + (s[i + 1] - '0') * 2 + (s[i + 2] - '0') * 1;
ans += (temp + '0');
}
cout << ans;
}
```

**Output:**

The octal equivalent of the given binary number is 146

**Time Complexity:** O(n), As we are traversing through only one for a loop.

**Space Complexity: **O(1).

## Java Code

```
public class Main {
public static void main(String args[]) {
String s = "1100110";
int n = s.length();
//adding appropriate "0" to the left of
//string to make the length divisible by 3.
if (n % 3 == 1) {
s = "00" + s;
} else if (n % 3 == 2) {
s = "0" + s;
}
n = s.length();
String ans = "";
for (int i = 0; i < n; i += 3) {
int temp = (s.charAt(i) - '0') * 4 + (s.charAt(i + 1) - '0') * 2 + (s.charAt(i + 2) - '0') * 1;
ans = ans + Integer.toString(temp);
}
System.out.print(ans);
}
}
```

**Output:**

The octal equivalent of the given binary number is 146

**Time Complexity:** O(n), As we are traversing through only one for a loop.

**Space Complexity: **O(1).

Special thanks to Pranav Padawe for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam,please check out this article