C++ Program For Binary To Octal Conversion
The problem is to convert the given binary number (represented as string) to its equivalent octal number. The input could be very large and may not fit even into unsigned long long int.
Input: 110001110 Output: 616 Input: 1111001010010100001.010110110011011 Output: 1712241.26633
The idea is to consider the binary input as a string of characters and then follow the steps:
- Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len.
- If left_len is not a multiple of 3 add min number of 0’s in the beginning to make length of left substring a multiple of 3.
- If right_len is not a multiple of 3 add min number of 0’s in the end to make length of right substring a multiple of 3.
- Now, from the left extract one by one substrings of length 3 and add its corresponding octal code to the result.
- If in between a decimal(‘.’) is encountered then add it to the result.
Octal number = 1712241.26633
Time Complexity: O(n), where n is the length of string.
Auxiliary space: O(1).
The steps for this approach are as follows:
- Convert the given binary number into groups of three digits starting from the rightmost side.
- Convert each group of three digits to its corresponding octal digit.
- Concatenate the octal digits obtained in step 2 to get the octal equivalent of the given binary number.
Octal equivalent of 110001110 is 616 Octal equivalent of 1111001010010100001 is 1712241 Octal equivalent of 11011.10 is 33.06314 Octal equivalent of 1002 is Invalid binary number
The time complexity of this approach is O(n), where n is the number of digits in the given binary number.
The auxiliary space required is O(n/3), since we need to store the octal digits obtained for each group of three binary digits.
My Personal Notes arrow_drop_up
Please Login to comment...