C++当中使用判断语句的经典算法题型(判断数字和字符字母、闰年、大小写转换、月份天数、三数当中的最大者、简单计算器)

1.判断数字和字符字母

class Solution {
public:
    /**
     * @param c: A character.
     * @return: The character is alphanumeric or not.
     */
    bool isAlphanumeric(char c) {
        return ((c>='0'&&c<='9')||(c>='A'&&c<='Z')||(c>='a'&&c<='z'));
    }
};

简单思想就是判断是否是位于0和9之间,或者是否位于大写字母A,Z 和小写字母a z之间

2.大小写转换

class Solution {
public:
    /**
     * @param character: a character
     * @return: a character
     */
    char lowercaseToUppercase(char character) {
        return toupper(character);
    }
};

在这里主要的思想就是使用C++当中的一个库函数toupper() ,转化为小写的库函数是tolower()

或者使用ASCII编码表,A=65,a=97,以此类推,每个小写字母与大写字母间隔32,所以小写字母转大写字母,直接小写字母-32就ok,大写字母转小写字母的话就+32

3.判断闰年

class Solution {
public:
    /**
     * @param n: a number represent year
     * @return: whether year n is a leap year.
     */
    bool isLeapYear(int n) {
        return (n%400==0||(n%4==0&&n%100!=0));
    }
};

4.月份天数

class Solution {
public:
    /**
     * @param year: a number year
     * @param month: a number month
     * @return: Given the year and the month, return the number of days of the month.
     */
    int getTheMonthDays(int year, int month) {
        // write your code here
        int days [] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
        if (month == 2){
            if (year%400==0||(year%4==0&&year%100!=0)){
            days[2] = 29;
        }
        }
        
        return days[month];
    }
    
};

5.三数当中的最大者

核心思想就是利用一个三目运算符

class Solution {
public:
    /**
     * @param num1: An integer
     * @param num2: An integer
     * @param num3: An integer
     * @return: an interger
     */
    int maxOfThreeNumbers(int num1, int num2, int num3) {
        int n=num1>num2?num1:num2;
        return n>num3?n:num3;
    }
};

6.简单计算器

就是一个非常简单的switch语句

class Calculator {
public:
    /**
     * @param a: An integer
     * @param op: A character, +, -, *, /.
     * @param b: An integer
     * @return: The result
     */
    int calculate(int a, char op, int b) {
        // write your code here
        switch(op)
        {
            case '+': return a+b;
            case '-': return a-b;
            case '*': return a*b;
            case '/': return a/b;
        }
    }
};

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值