You can say 11
题目连结
题目
Your job is, given a positive number N, determine if it is a multiple of eleven.(until input 0)
sample input112233 30800 2937 323455693 5038297 112234 0
sample output112233 is a multiple of 11.30800 is a multiple of 11.2937 is a multiple of 11.323455693 is a multiple of 11.5038297 is a multiple of 11.112234 is not a multiple of 11.
题目翻译
找出是输入否为11的倍数(直到输入为0)
解题
是不是觉得只要对输入取11的余数
为0就行了?
会超时
会超时
会超时
怎么办呢?
只要知道这个原理就能秒杀了
(偶数位置之合-奇数位置之合)除11取余数(从最左边来看)
如果是0==>是
反之==>否
证明
以112233为例
偶数位置1+2+3=6
奇数位置1+2+3=6
(6-6)%11=0&11=0
再以30800为例
偶数位置3+8+0=11
奇数位置0+0+0=0
(11-0)%11=0
112234
偶数位置1+2+3=6
奇数位置1+2+4=7
(6-7)%11=-1(不是)
利用这个技巧,就可以避免对一个很大的数字进行除法,节省时间
code
#include <iostream>#include <string.h>using namespace std;/* 题目:You can say 11 题目来源:online judge 题目连结:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1870 解题语言:c++ 解题者:神里绫华的狗 解题连结:*/int main(){ string s; while (cin >> s) { if (s == "0") break; int a = 0, b = 0; for (int i = 0; i < s.length(); i++) { //字串转化数字 int n = s[i] - '0'; //偶数位置分到这 if (i % 2 == 0) a += n; //奇数位置分到这 else b += n; } if ((a - b) % 11 == 0) cout << s << " is a multiple of 11." << endl; else cout << s << " is not a multiple of 11." << endl; } return 0;}