第47题:求1+2+3+...+n
难易度:⭐
题目描述:
求1+2+3+...+n
要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
本题使用一种比较鸡贼的写法,利用了&&运算的短路特性
代码如下:
public class Solution {
public int Sum_Solution(int n) {
int res = n;
boolean flag = (n > 1) && ((res += Sum_Solution(n - 1)) > 1);
return res;
}
}
第48题:不用加减乘除做加法
难易度:⭐
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
本题我没有想出来,直接看了答案。
如果要求不使用加减乘除,那么可以想到位运算
- 两个数异或:相当于每一位相加,而不考虑进位的情况
- 两个数进行与运算,并左移一位,相当于求得进位
- 将两个步骤结合起来
代码如下:
public class Solution {
public int Add(int num1,int num2) {
while(num2 != 0){
int res = num1 ^ num2;
num2 = (num1 & num2) << 1;
num1 = res;
}
return num1;
}
}