题解 | #游游的数字圈#
游游的数字圈
https://www.nowcoder.com/practice/16eafa41a4a242b8870cb2c5420ae089
解题思路
统计字符串中每个数字的圆圈数:
- 数字0、6、9各包含1个圆圈
 - 数字8包含2个圆圈
 - 其他数字(1,2,3,4,5,7)不包含圆圈
 
遍历字符串,累加每个数字对应的圆圈数即可。
代码
#include <iostream>
#include <string>
using namespace std;
int countCircles(string num) {
    int count = 0;
    for(char c : num) {
        if(c == '0' || c == '6' || c == '9') {
            count += 1;
        } else if(c == '8') {
            count += 2;
        }
    }
    return count;
}
int main() {
    string num;
    cin >> num;
    cout << countCircles(num) << endl;
    return 0;
}
import java.util.Scanner;
public class Main {
    public static int countCircles(String num) {
        int count = 0;
        for(char c : num.toCharArray()) {
            if(c == '0' || c == '6' || c == '9') {
                count += 1;
            } else if(c == '8') {
                count += 2;
            }
        }
        return count;
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String num = sc.next();
        System.out.println(countCircles(num));
        sc.close();
    }
}
def count_circles(num):
    count = 0
    for c in num:
        if c in ['0', '6', '9']:
            count += 1
        elif c == '8':
            count += 2
    return count
if __name__ == "__main__":
    num = input()
    print(count_circles(num))
算法及复杂度
- 算法:字符串遍历。遍历输入的数字字符串,根据每个数字包含的圆圈数进行统计。
 - 时间复杂度:
,其中n是输入字符串的长度,需要遍历整个字符串。
 - 空间复杂度:
,只使用了常数级别的额外空间。
 
查看12道真题和解析