技巧之 -- 8 的倍数
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.
Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.
If a solution exists, you should print it.
Input
The single line of the input contains a non-negative integer n. The representation of number n doesn't contain any leading zeroes and its length doesn't exceed 100 digits.
Output
Print "NO" (without quotes), if there is no such way to remove some digits from number n.
Otherwise, print "YES" in the first line and the resulting number after removing digits from number n in the second line. The printed number must be divisible by 8.
If there are multiple possible answers, you may print any of them.
Example
Input
3454
Output
YES
344
Input
10
Output
YES
0
Input
111111
Output
NO
題目分析 :
給你一個長度小于 100 的串,讓你刪除其中的一些字符,讓剩下的數是 8 的倍數,如果沒有輸出 NO
思路分析 :
這個題當時是沒有寫出來的,發現自己好笨 ... 連自己打個表看下規律都找不到,只要你打個 2000 以內的表就能發現規律,你會發現只要之后 3位是 8的倍數,不管它前面是什么數字,那么這個數一定是8的倍數
至于證明呢,我就只有一個比較 low 的辦法了,因為最小的4位數是1000, 它是 8 的倍數,那么它在加上一個是 8倍數的三位數一定就能得到一個是8倍數的3位數。
那么根據這個簡單的證明,我們是不就能得到進一步推廣,比如我們將這個題 的對 8 的判斷更改為對 125 的判斷,同樣也是先看最小的四位數是 1000,只要求它最后的三位是 125的倍數就可以了
代碼示例 :
char pre[105];
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
scanf("%s", pre+1);
int len = strlen(pre+1);
for(int i = 1; i <= len; i++){
int num = pre[i] - '0';
if (num % 8 == 0) {printf("YES
%d
", num); return 0;}
for(int j = i+1; j <= len; j++){
int num = 10*(pre[i]-'0') + (pre[j]-'0');
if (num % 8 == 0) {printf("YES
%d
", num); return 0;}
for(int k = j+1; k <= len; k++){
int num = 100*(pre[i]-'0') + 10*(pre[j]-'0') + (pre[k]-'0');
if (num % 8 == 0) {printf("YES
%d
", num); return 0;}
}
}
}
printf("NO
");
return 0;
}
東北日出西邊雨 道是無情卻有情
總結
以上是生活随笔為你收集整理的技巧之 -- 8 的倍数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: randperm函数
- 下一篇: 备胎能开多久(小备胎最多用多久)