方法1(推荐)
复制代码
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/* 双向队列 推荐 余数插入头部,从尾部逐渐取出 */ void DecimalToBinary(int value) { int num = 0; deque<int> 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
复制代码
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/* 堆栈 */ void DecimalToBinary(int value) { //先进后出 int num = 0; stack<int> 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
复制代码
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/* vector 容器 */ void DecimalToBinary(int value) { int num = 0; vector<int> 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++ 面试题:求十进制转为2进制数中1的个数方法1(推荐)方法2方法3的全部内容,更多相关C++内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复