【题解】T156526 各数字之和

审题

这题一看数据范围就是裸的暴力……

对于 (1sim n) 之间的每一个整数,我们把它的每一位拆分,再相加,得到每一位的和,在判断这个和是否等于 (9),如果是,ans++

解法

拆分的方法如下:

  1. 将这个数%10取得它的最后一位
  2. 将这个数/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),返回 (true)。我直接拿 (ans) 加上这个值,(true) 就会自动转换为 (1)(false) 就自动转换为 (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;
}

简单明了。

原文地址:https://www.cnblogs.com/g-mph/p/14636555.html