Here is my code for "Reverse Binary Numbers" in C.
Problem
Your task will be to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11.
Input
The input contains a single line with an integer \$N\$, (where \$1≤N≤1000000000\$ ).
Output Output one line with one integer, the number we get by reversing the binary representation of \$N\$.
Sample 1
- input
13
- output
11
Sample 2
- input
47
- output
61
It's pretty efficient, but not the best. I wanted to improve the runtime. So I am looking for suggestions to improve the code.
Code
//Reverse Binary
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DIVISOR 2
#define MAX 50
int main() {
int r, q, n, m = 1, num = 0, i = 0, len;
int res[MAX];
char str[MAX];
scanf("%d", &n);
do {
q = n / DIVISOR;
r = n % DIVISOR;
res[i] = r;
n = q;
i++;
} while(n > 0);
len = i;
m = 1;
for(; i > 0; i--) {
if(res[i - 1] != 0) {
num += res[i - 1] * m;
}
m *= DIVISOR;
}
fprintf(stdout, "%d", num);
return 0;
}