//把数字拆开 //一个数字若能被3整出,则它的各个位上的数字相加可以被3整出 //所以题目其实是求,数字的组合,使子串的各位相加可以被3整出 //一个数字,除以3,余数为0,1,2 //所以,可以把字符串直接当作它的余数串 //892213467 //202210101 //1.把0单独领出来,认为可以被3整出 //2.尽量每次分的越少越好 //3.现在只考虑1和2的情况 //111 //222 //1和2交替,一旦出现了既有1又有2,那么可以被3整出 #include <iostream> #include <string> //现在开始循环遍历 using namespace std; int main() { string str; cin >> str; int leng = str.size(); int count = 0;//count用来统计可以整除3的个数 int num = 0;//用来统计当前数字的总和 int c1 = 0; int c2 = 0; //c1和c2分别统计当前余数为1和余数 for(int i=0;i<leng;i++) { //str[i]为字符,str[i]-'0'为数字 int now = str[i] - '0'; if (now % 3 == 0) { count++; c1 = 0; c2 = 0; num = 0; } else if (now % 3 == 1) { num+=str[i]; c1++; } else { num+=str[i]; c2++; } //再次判断能否组合成一个字符串 if ((num > 0 && num % 3 == 0) || (c1&&c2)) { count++; c1 = 0;c2 = 0;num = 0; } } cout << count << endl; system("pause"); return 0; }
点赞 评论

相关推荐

牛客网
牛客网在线编程
牛客网题解
牛客企业服务