1.题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。(google面试题)
例如 输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。
分析:这是一道广为流传的google面试题
例如 输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。
分析:这是一道广为流传的google面试题
1 #include <stdio.h>
2 int main()
3 {int count=0;
4 int i,a;
5 int n;
6 scanf("%d",&n);
7 for (i=1;i<=n;i++)
8 {
9 a=i;
10 while(a>0)
11 {
12 if(a%10==1)
13 {
14 ++count;
15 }
16 a=a/10;
17 }
18 }
19 printf("%d",count);
20 return 0;
21 }
2.题目:编写程序,将十进制转换为8进制并输出(不允许使用printf("%o"))
1 #include <stdio.h>
2 int main()
3 {
4 int a,n,i;
5 int b=0,t=1;
6 printf("please input: ");
7 scanf("%d",&n);
8 while(n!=0)
9 {
10 for(i=0;i<1;i++)
11 {
12 a=n%8;
13 n=n/8;
14 }
15 b=(a*t)+b;
16 t=t*10;
17 }
18 printf("The output is :%d",b);
19 return 0;
20 }
3.
总结:
1. const char* 字符串 以 “\0”结尾。
2. char[] 字符串 以 “\0”结尾。
3.string 字符串 不以 “\0”结尾。
4. char[n] = "string", 当string 长度+“\0”>n时,会因空间不足出错。
5.string.c_str() 转 const char* 时, 会在字符串末尾 自动补“\0”
6.char* 转string 时, 会自动把末尾的 “\0” 去掉。
7.strlen()是取字符串除去结尾符 “\0” 的长度。