我正在尝试将LeetCode问题计数为0的问题。我想我已经接近了,但是我的变量num总是打印0,我怀疑它正在递减计数,但是直到完成为止才打印。请看一下我的代码。
#include <stdio.h>
#include <iostream>
using namespace std;
class Solution {
public:
int num;
int numberOfSteps (int num)
{
while (num != 0)
{
if (num % 2 == 0)
{
num = num / 2;
cout << num;
}
else
{
num = num - 1;
cout << num;
}
}
}
};
int main () {
int num;
Solution myObj;
cin >> num;
cout << myObj.num;
}
您正在将数字传递给std::cout
。您也不会在代码中的任何地方调用numberOfSteps(...)
。
用cout << myObj.numberOfSteps(num);
替换行可以解决此问题,但更简洁的解决方案如下:
#include <stdio.h>
#include <iostream>
using namespace std;
void countDown (int num) {
while (num != 0) {
if (num % 2 == 0) {
num = num / 2;
cout << num << endl;
} else {
num = num - 1;
cout << num << endl;
}
}
}
int main () {
int num;
cin >> num;
countDown(num);
}
不需要类,因为没有状态,并且函数为void
,因为它不返回任何东西。