天天看點

資訊學奧賽一本通 1982:【19CSPJ普及組】數字遊戲

【題目連結】

ybt 1982:【19CSPJ普及組】數字遊戲

【題目考點】

1. 字元串處理

  • 用字元數組,或用string類

2. 分離各位數字

【題解代碼】

解法1:用字元數組,統計字元串中字元’1’的個數

#include <bits/stdc++.h>
using namespace std;
int main()
{
	char s[10];
	cin>>s;
	int len = strlen(s), ct = 0;//ct:計數 
	for(int i = 0; i < len; ++i)
	{
	    if(s[i]=='1')
	       ct++;
    }
    cout<<ct;
    return 0;
}
           

解法2:使用string類

#include <bits/stdc++.h>
using namespace std;
int main()
{
	string s;
	cin>>s;
	int ct = 0;//ct:計數 
	for(int i = 0; i < s.length(); ++i)
	{
	    if(s[i]=='1')
	       ct++;
    }
    cout<<ct;
    return 0;
}
           

解法3:分離整數各位數字

将01字元串視為一個十進制整數。8位數可以由int型量表示。

通過分離各位數字的方法,統計其中1的個數。

#include <bits/stdc++.h>
using namespace std;
int main()
{
	int n, ct = 0;
	cin>>n;
	for(int a = n; a > 0; a /= 10)
    {
        if(a % 10 == 1)
            ct++;
    } 
    cout<<ct;
    return 0;
}