C++ 面试题:求十进制转为2进制数中1的个数

方法1(推荐)

/*
双向队列  推荐
余数插入头部,从尾部逐渐取出
*/
void DecimalToBinary(int value)
{
	int num = 0;
	deque deq;
	while (value != 0)
	{
		int pop = value % 2;        //取余数
		value /= 2;
		deq.push_front(pop);       //插入头部
	}
	//打印
	for (auto it = deq.begin(); it != deq.end(); it++)
	{
		cout << *it;
		if (*it==1)
		{
			++num;
		}
	}
	cout << endl;
	cout << num << endl;
}

方法2

/*
堆栈
*/
void DecimalToBinary(int value)
{
	//先进后出
	int num = 0;	
	stack st,st2;
	while (value != 0)
	{
		int pop = value % 2;   //取余数
		value /= 2;
		st.push(pop);
		if (pop==1)            //计算1的个数
		{
			st2.push(pop);
		}
	}
	//打印
	while (!st.empty())
	{
		cout << st.top();
		st.pop();
	}
	cout << endl;
	cout << st2.size() << endl;
}

方法3

/*
vector 容器
*/
void DecimalToBinary(int value)
{
	int num = 0;
	vector vec;
	while (value != 0)
	{
		int pop = value % 2;   //取余数
		value /= 2;
		vec.push_back(pop);
	}
	//打印
	for (auto it = vec.size(); it>0; it--)
	{
		if (vec[it-1]==1)
		{
			num++;            //计算1的个数
		}
		cout << vec[it-1];
	}
	cout << endl;
	cout << num << endl;
}

你可能感兴趣的:(每日一题,c++,动态规划,链表)