티스토리 뷰


[프로그래밍 문제] 재귀를 이용해서 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;
	}
}


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


댓글