Algorithm:
1. take input x
2. Initialize r := 0,cb = 0;
3. while(x!=0) Begin
4. cb := cb+1, r := left shift by 1 bit
5. r :=r + (x&1)
6. n:= right shift by 1;
7. End
Complexity: O(cb), cb = bit length of the number
How do we display the bits of the number?
Algorithm :
1. For i=1:cb Begin
2. display r&1
3. r:= right shift by 1
4.End
1. take input x
2. Initialize r := 0,cb = 0;
3. while(x!=0) Begin
4. cb := cb+1, r := left shift by 1 bit
5. r :=r + (x&1)
6. n:= right shift by 1;
7. End
Complexity: O(cb), cb = bit length of the number
How do we display the bits of the number?
Algorithm :
1. For i=1:cb Begin
2. display r&1
3. r:= right shift by 1
4.End
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> int main() { int n,tn,cb=0,r=0; scanf ("%d",&n); tn=n; while(tn!=0){ cb++; r=r<<1; r= r | (tn&1); tn = tn>>1; } printf("Input: %d Length: %d Bit string:",n,cb); for (tn=1;tn<=cb;tn++){ printf("%d",(r>>(tn-1))&1); } printf("\n"); return 0; } |
Sample Output: 12 Input: 12 Length: 4 Bit string:1100
No comments:
Post a Comment