我正在编写一些代码以在培训站点上以二进制形式分解数字。我已经在我的本地编译器上测试了一百次,它工作得很好,但是培训网站告诉我有错误。
(我的代码既不优雅也不高效,尤其是循环,但我分解了代码以了解错误可能在哪里)。谁能告诉我是否有错误?
#include <stdio.h>
#include <stdlib.h>
//function that displays the greatest power of 2 less than a fixed number N
int residu(int N)
{
int i;
int M=2;
for(i=0;i<N;i++){
if(M>N){break;}else{M=2*M;i++;}
}
return M/2;
}
int main()
{
int i;
//N is the input to decompose
int N;
scanf("%d",&N);
//We will search for the greatest power of 2 less than a fixed number N,
//than repeating the some process with the residue of N with the greatest power of 2 //less than N, so we have to store the value of N for the loop (see below) we will use to work //correctly
int M;
M=N;
//D displays the diffrence betwenn two successive powers of 2 that appears in the //binary decomposition, (we will then print "O")
int D;
D=log(residu(N))/log(2);
for(i=0;i<M;i++){
//If N==residu(N), the decomposition is finished
if(N==residu(N)){printf("1");int k;
for(k=0;k<D;k++){printf("0");}break;}
else{
// N is a the residue of the former value of N and the greatest power of 2 //less than N
N=N-residu(N);
D=D-log(residu(N))/log(2);
printf("1");
int k;
for(k=0;k<D-1;k++){printf("0");
}
D=log(residu(N))/log(2);
}
}
}