借的图,讲的很详细
- 这一题中的4^x所占的奇偶数不同来找规律,然后分情况计算10000和10010这两种除最高位是否还有1的情况,有1的话就strlen(str)/2+1,否则就strlen(str)/2。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
方法一: #include<iostream> #include<cstring> using namespace std; string s; int i,j; int ans; int cnt; int main() { cin>>s; int n=s.length()-1;//减1的目的就是不统计最高位的数值为1还是0(因为最高位的数值一定为 1,即s) for(i=0;i<=n;i++) { if(s[i]=='1') cnt++;//统计所有位置的1的情况(包括最高位) } if(n%2==0&&cnt==1) //这就是10000的那种情况 ans=n/2; else if(n!=0) ans=n/2+1; else ans=0; cout<<ans; return 0; } 方法二: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include<iostream> using namespace std; int main() { char str[200]; scanf("%s", str); int len = strlen(str); cout<<len<<endl; cout<<(len%2)<<endl; int m = 0; if (len % 2 == 1) { for (int i = 1; i < strlen(str); i++) {//少统计最高位的那个位的数(str[0])为0 or 1,因为最高位是奇数位然后后面没有1和最高位是偶数的情况可以归为一类,即ans=len/2 int t = str[i] - '0'; m = m + t; } } if (m > 0) { m = 1; } int ans = len / 2 + m; printf("%d\n", ans); return 0; } 小知识: #include<iostream> #include<cstring> using namespace std; int main(){ char s[3]; cin>>s; cout<<s[0]<<s[1]<<s[2]; //输入:abc;输出cba,即c为s[0] } 相应的可以用for循环来高低位互换 #include<iostream> #include<cstring> using namespace std; int main(){ string ss; cin>>ss; char s[100]; int n=ss.size(); for(int i=0;i<n;i++){ //换n位,下标为0与下标为n-1互换,1与n-2互换 s[i]=ss[n-i-1]; } for(int i=0;i<n;i++){ cout<<s[i]; } }