Write a program to convert decimal number to binary string
The approach:-- Initialize a string array to hold the output binary string.
- mod the input number by 2. If reminder is '1' include '1' in the output string. Else include '0'.
- Divide the number by 2 for next iteration.
- Repeat steps 2 and 3 till number becomes 0.
- Reverse the string to get the output sequence.
C++ program to convert decimal number to binary string
#include <iostream> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; char* dec2bin(int n) { char* str = (char*)malloc(sizeof(32)); char bin_str[] = { '0', '1' }; int count = 0; while ( n > 0 ) { int rem = n % 2; n = n / 2; rem ? str[count] = bin_str[1] : str[count] = bin_str[0]; count++; } str[count] = '\0'; // reverse the string int size = strlen(str) - 1; for ( int i = 0; i <= size/2; i++ ) { char ch = str[i]; str[i] = str[size - i]; str[size - i] = ch; } return str; } int main() { int n = 100; cout << dec2bin(n) << endl; }Output:-
1100100
0 comments:
Post a Comment