41.题目描述

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
class Solution {
public:
    int Sum_Solution(int n) {
        
        char a[n][n+1];
        return sizeof(a)>>1;
        
    }
};
View Code

42.题目描述

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
class Solution {
public:
    int Add(int num1, int num2)
    {
        if(num1 == 0)
           return num2;
        if(num2 == 0){
            return num1;
        }
        return Add(num1^num2,(num1&num2)<<1);
        
    }
};
View Code

43.题目描述

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 
class Solution {
public:
    int StrToInt(string str) {
        
        if(str.length()==0){
            return 0;
        }
        int symbol = 0;
         int val = 0;
        if(str[0]=='+'){
            symbol=1;
        }else if(str[0]=='-'){
            symbol=-1;
        }else if(str[0]-'0'>=0 && str[0]-'0'<10){
            val = str[0]-'0';
             symbol=1;
        }
        
       
        for(int i=1;i<str.length();i++){
            
            if(str[i]-'0'>10 || str[i]-'0'<0){
                return 0;
            }
            val = val*10 + str[i]-'0';
            
        }
        return val*symbol;
        
    }
};
View Code

相关文章: