2.递归-求一个整数(十进制)的二进制

#include <stdio.h>
int to_binary(int a);
int main()
{
  
  //求一个整数(十进制)的二进制(循环语句版)
  int a = 1234;
  int result;
  int shang;

  int size;
  int re;
  int b = a;
  int c = a;
  //获取int数组的长度
    while( ( re = b / 2 ) != 0  )
    {
        b = b / 2; 
        size++;

    }
    //printf("size: %d\n", size + 1);
    int stack[size+1];
    int index = 0;
    
    //将数据装载到数组中
    while(1)
    {  

      if( (shang = a / 2) == 0)
      {
        result = a % 2;
        //printf("%d\n",result );
        stack[index++] = result;
        break;
      }else{
        result = a % 2;
        //printf("%d\n",result );
        stack[index++] = result;
        a = a / 2;
      }

    }

      //打印数组
      printf("循环方式:");
      for (int i = size; i >= 0; i--)
      {
          printf("%d", stack[i]);
            
      }
      printf("\n");
      printf("递归方式:");
      
      to_binary(c);
      printf("\n");


    return 0;
}

int to_binary(int a)
{
    int r = a % 2;
    if(a / 2 != 0)
      to_binary(a / 2);

    printf("%d",r );

    return 0;
    
}

 

上一篇:LeetCode 401. Binary Watch(二进制手表)


下一篇:利用U盘制作Win To Go