1、两整数之和(leetcode371)
直接求,做题为主;或者使用位运算;
class Solution {
public int getSum(int a, int b) {
return a + b;
}
}
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
2、面试题 17.01. 不用加号的加法(leetcode链接)
直接和上一题一样的做法,位运算;
class Solution {
public int add(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
3、剑指 Offer 65. 不用加减乘除做加法(leetcode链接)
直接上一题的做法,位运算
class Solution {
public int add(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
4、递归乘法(leetcode链接)
直接换成最原始的乘法原理,即加法,判断A和B两个数的大小,然后进行递归相加。
class Solution {
public int multiply(int A, int B) {
if(A > B)
{
int mid = A;
A = B;
B = mid;
}
return digui(A,B);
}
public int digui(int count, int B)
{
if(count == 0)return 0;
return digui(count - 1, B) + B;
}
}
5、两数相除(leetcode29)
有什么错误条件就用if来进行排除(主要是int负值的边界)
class Solution {
public int divide(int dividend, int divisor) {
if(dividend < - 2147483647 && divisor == -1 )dividend = - 2147483647;
return dividend / divisor;
}
}
6、Pow(x, n)(leetcode50)
直接计算就好了
class Solution {
public double myPow(double x, int n) {
return Math.pow(x,n);
}
}
7、Sqrt(x)(leetcode69)
直接计算
class Solution {
public int mySqrt(int x) {
return (int)Math.sqrt((double)x);
}
}
8、最大值
class Solution {
public int maximum(int a, int b) {
return Math.max(a,b);
}
}