top1编程
← 返回题目
题解

字符判断

1 条题解

  • 0
    @ 2026-8-4 9:54:08

    解题思路

    字符的 ASCII 码连续,所以可以用比较大小判断它属于哪一类:

    • 大写字母:'A' ≤ c ≤ 'Z'
    • 小写字母:'a' ≤ c ≤ 'z'
    • 数字:'0' ≤ c ≤ '9'
    • 其他字符

    参考代码

    #include <iostream>
    using namespace std;
    
    int main() {
        char c;
        cin >> c;
        if (c >= 'A' && c <= 'Z') cout << "capital" << endl;       // 大写字母
        else if (c >= 'a' && c <= 'z') cout << "lowercase" << endl; // 小写字母
        else if (c >= '0' && c <= '9') cout << "number" << endl;    // 数字
        else cout << "others" << endl;                              // 其他字符
        return 0;
    }
    

    复杂度分析

    最多判断 4 次,时间复杂度 O(1),额外空间复杂度 O(1)。

    • 1