2235. 两整数相加
源码剖析class Solution {
public:
int sum(int num1, int num2) {
return num1+num2;
}
};
直接返回即可。
2.力扣剑指 Offer II 072. 求平方根 原题链接剑指 Offer II 072. 求平方根
源码剖析class Solution {
public:
int mySqrt(int x) {
return (int)sqrt(x);
}
};
先暂且使用库函数实现。
3.力扣69 原题链接69. x 的平方根
源码剖析class Solution {
public:
int mySqrt(int x) {
return (int)sqrt(x);
}
};
同上
4.力扣367 原题链接367. 有效的完全平方数
源码剖析class Solution {
public:
bool isPerfectSquare(int num) {
long long ans = 0;
for(int i = 0;i<=num;++i){
if((long long)i*i<=num){
ans = i*i;
}else break;
}
return ans==num;
}
};
注意数据溢出的问题,i*i 要转为 long long。
5.力扣剑指 Offer 16. 数值的整数次方 原题链接剑指 Offer 16. 数值的整数次方
源码剖析class Solution {
public:
double myPow(double x, int n) {
return pow(x,n);
}
};
二分快速幂日后学习。
6.力扣50 原题链接50. Pow(x, n)
源码剖析class Solution {
public:
double myPow(double x, int n) {
return pow(x,n);
}
};
同上
7.力扣231 原题链接231. 2 的幂
源码剖析class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0&&(n&(n-1))==0;
}
};
一个整数如果是 2 的幂次方必然满足这个数是大于 0 的,而且其写为二进制之后有如下的形式 10000…00 所以使其减去 1 后会变为 011111…111 的形式,那么两数位与之后必然等于 0 。
8.力扣326 原题链接326. 3 的幂
源码剖析class Solution {
public:
bool isPowerOfThree(int n) {
while(n!=0&&n%3==0){
n/=3;
}
return n==1;
}
};
满足是 3 的幂的数首先肯定能被整除,其次当其不断除去 3 之后,最终一定会等于 1 。
9.力扣342 原题链接342. 4的幂
源码剖析class Solution {
public:
bool isPowerOfFour(int n) {
while(n&&n%4==0){
n/=4;
}
return n==1;
}
};
同上。
10.力扣面试题 16.01. 交换数字 原题链接面试题 16.01. 交换数字
源码剖析class Solution {
public:
vector swapNumbers(vector& numbers) {
vector ret;
ret.push_back(numbers[1]);
ret.push_back(numbers[0]);
return ret;
}
};
这里练习一下使用 vector 类,实际上可以直接使用位运算。



