티스토리 뷰

코드 스니펫 복사

[프로그래밍 문제] 재귀를 이용해서 10진수를 2진수로 바꾸기


 (Recursive decimal to binary)
Write a RECURSIVE FUNCTION that converts and displays a decimal number to a

binary number. Note that the function “display_dec2bin_resursive” which you must write, does not display

“endl", so it is displayed in the function main.
 

#include <iostream>

using namespace std;
 

void display_dec2bin_resursive( int decnum )

{

// IMPLEMENT THIS FUNCTION

}
 

int main()

{

int decnum;

while (1) {

cin >> decnum;

if ( decnum == -99 ) break;

else display_dec2bin_recursive(decnum);

cout << endl;

}

}
 

[Example output]

[gjang@unimaster1 week9ex]$ w9q2

1 2 7 11 31 45 101 1000 2048 -99

1

10

111

1011

11111

101101

1100101

1111101000

100000000000

[gjang@unimaster1 week8ex]$

No input




저는 아래와 같이 소스를 짜 보았습니다. 

 
#include <iostream>
using namespace std;

void display_dec2bin_resursive( int decnum )
{
	if ( decnum >= 2 )
	{
		display_dec2bin_resursive ( decnum /2 ) ;
		cout << decnum % 2 ;
	}
	else if ( decnum == 1 )
		cout << "1" ;
}

int main()
{
	int decnum;
	while (1) {
		cin >> decnum;
		if ( decnum == -99 ) break;
		else display_dec2bin_resursive(decnum);
		cout << endl;
	}
}


결과는 아래와 같았습니다.


신고
댓글
댓글쓰기 폼
공지사항
Total
2,511,657
Today
684
Yesterday
1,125
«   2017/11   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    
글 보관함