审题
这题一看数据范围就是裸的暴力……
对于
1
∼
n
1\sim n
1∼n 之间的每一个整数,我们把它的每一位拆分,再相加,得到每一位的和,在判断这个和是否等于
9
9
9,如果是,ans++
。
解法
拆分的方法如下:
- 将这个数%10取得它的最后一位
- 将这个数/10删除它的最后一位
拆分的代码如下:
bool num(int n) {
int ans = 0;
while (n) { //当n == 0时停止
ans += n % 10; //取最后一位相加
n /= 10; //删除最后一位
}
if (ans == 9) return true;
return false;
}
代码
我偷了个懒,因为如果每一位相加等于 9 9 9,返回 t r u e true true。我直接拿 a n s ans ans 加上这个值, t r u e true true 就会自动转换为 1 1 1, f a l s e false false 就自动转换为 0 0 0。
完整的代码如下:
#include <iostream>
using namespace std;
bool num(int n) {
int ans = 0;
while (n) { //当n == 0时停止
ans += n % 10; //取最后一位相加
n /= 10; //删除最后一位
}
if (ans == 9) return true;
return false;
}
int main() {
int n, ans = 0;
cin >> n;
for (int i = 1; i <= n; i++)
ans += num(i);
cout << ans << endl;
return 0;
}
简单明了。