C. Divisibility by Eight
大致题意:
给出一个字符串,删除一些(或者0个)数字,使得剩余数字可以整除8,并输出"YES"和删除后的数字,否则输出"NO"
解题思路:
数学结论:只要尾部有三位数是8的倍数,那么这个数就能被8整除
暴力枚举,枚举一位,两位,三位的情况即可
复杂度:O(n3) n<=100
AC代码:
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
#define debug(c) cout << #c << " = " << c << endl;
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int N = 1e6 + 10;
int n, m;
char s[110];
int main(void) //
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
ios::sync_with_stdio(0); cin.tie(0);
cin >> s + 1;
n = strlen(s + 1);
for (int i = 1; i <= n; ++i) { //一位
int x = s[i] - '0';
if (x % 8 == 0) {
cout << "YES" << endl << x << endl;
return 0;
}
}
for (int i = 1; i <= n; ++i) //两位
for (int j = i + 1; j <= n; ++j) {
int x = (s[i] - '0') * 10 + s[j] - '0';
if (x % 8 == 0) {
cout << "YES" << endl << x << endl;
return 0;
}
}
for (int i = 1; i <= n; ++i) //三位
for (int j = i + 1; j <= n; ++j)
for (int k = j + 1; k <= n; ++k) {
int x = (s[i] - '0') * 100 + (s[j] - '0') * 10 + s[k] - '0';
if (x % 8 == 0) {
cout << "YES" << endl << x << endl;
return 0;
}
}
cout << "NO" << endl;
return 0;
}