static const auto speedup=[]{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return 0;
}();//可以加速执行
Problem 7:
class Solution {
public:
int reverse(int x) {
long long ans = 0;
const int maxint = 0x7fffffff;//注意判断最大整数与最小整数
const int minint = 0x80000000;
while(x != 0){
ans = ans * 10 + (x % 10);
x = x / 10;
}
if(ans < minint || ans > maxint)//同上
ans = 0;
return ans;
}
};
Problem 8:
class Solution {
const int maxint = 0x7fffffff;//判断最大正值
const int minint = 0x80000000;//判断最大负值
const long long max = 0x100000000;//判断绝对最大值
public:
int myAtoi(string str) {
long long ans = 0;
bool flag = false;//记录正负性
int st = 0;
while(st < str.length() && str[st] == ' '){//考虑极端情况:误输入空格
st++;
}
if(st < str.length() && str[st] == '+') //寻找正号
{
st++;
}
else{
if(st < str.length() && str[st] == '-'){//寻找负号
flag = true;
st++;
}
}
for(int i=st;i < str.length();i++){
if(str[i] <= '9' && str[i] >= '0'){
ans = ans*10 + str[i] - '0';
if(ans > max) ans = max;//判断绝对溢出
}
else
break;
}
if(flag) ans = -ans;
if(ans > maxint) ans = maxint;
if(ans < minint) ans = minint;
return ans;
}
};
总结:
0,负数,正数,最大正值(0x7fffffff),最小负值(0x80000000)溢出问题的情况都需要考虑
231.Power of Two (43:12--57:42)
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n <= 0)
return false;
return ((n & (n-1)) == 0);//举个例子理解一下
//可以看到将原来的最右边的1变为0了。
}
};
Power of Four
class Solution {
public:
bool isPowerOfFour(int num) {
//2 8 false
//4 16 true
//5 0101
//0101 & 1000 = 0000
//0101 & 0100 = 0100
if(num <= 0) return false;
return ((num&(num-1)) == 0 && (num&0x55555555));
}
};
Power Of Three:
static const auto speedup=[]{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return 0;
}();//可以加速执行
class Solution {
public:
bool isPowerOfThree(int n) {
return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0);
}
};
191.位1的个数
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while(n > 0){//若等于0了,n&(n-1)<0
n = n&(n-1);//将最右面的1置为0
ans++;
}
return ans;
}
};
总结:
172.阶乘后的零的个数
/*
首先题目的意思是末尾有几个0
比如6! = 【1* 2* 3* 4* 5* 6】
其中只有2*5末尾才有0,所以就可以抛去其他数据 专门看2 5 以及其倍数 毕竟 4 * 25末尾也是0
比如10! = 【2*4*5*6*8*10】
其中 4能拆成2*2 10能拆成2*5
所以10! = 【2*(2*2)*5*(2*3)*(2*2*2)*(2*5)】
一个2和一个5配对 就产生一个0 所以10!末尾2个0
转头一想 2肯定比5多 所以只数5的个数就行了
假若N=31 31里能凑10的5为[5, 2*5, 3*5, 4*5, 25, 6*5] 其中 25还能拆为 5**2
所以 里面的5的个数为 int(31/(5**1)) + int(31/(5**2))
所以 只要先找个一个 5**x < n 的x的最大数 然后按上面循环加起来
*/
static const auto speedup=[]{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return 0;
}();//可以加速执行
class Solution {
public:
int trailingZeroes(int n) {
int ans = 0;
while(n > 0){
ans += n/5;
n /= 5;
}
return ans;
}
};
总结:阶乘后的0