1.常见面试题型atoi
解题技巧:数据大小:maxint:0x7fffffff 2147483647
minint:0x80000000 -2147483648
数字的转置
class Solution {
public:
int reverse(int x) {
//x=1999999999
long long ans=0;
const int maxint=0x7fffffff;
const int minint=0x80000000;
while(x!=0){
ans=ans*10+(x%10);
x/=10;
}
if(ans<minint||ans>maxint)
{ans=0;}
return ans;
}
};
字符串转整数
class Solution {
public:
int myAtoi(string str) {
const int maxint=0x7fffffff;
const int minint=0x80000000;
const long long max=0x100000000;
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>maxint) ans=maxint;
}else
{break;}
}
}
if( flag ==true ) ans=-ans;
if(ans>maxint)
ans=maxint;
if(ans<minint)
ans=minint;
return ans;
};
4的幂
class Solution {
public:
bool isPowerOfFour(int num) {
//2 8 false 2=10 8=1000
//4 16 false
//5 101
if(num<=0) return false;
return((num&(num-1))==0 &&(num&0x55555555));
}
};
位1的计算
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans=0;
while(n>=0)
{
n=n&(n-1);//置最低位1为0
ans++;
}
return ans;
}
};
3的幂
class Solution {
public:
bool isPowerOfThree(int n) {
//3 9 27
//big3%n==0
//big3=3^k
//k=log3(maxint)
if(n<=0) return false;
const int maxint=0x7fffffff;
int k=log(maxint)/log(3);
int big3=pow(3,k);
return (big3%n==0);
}
};
各位相加
class Solution {
public:
int addDigits(int num) {
if(num==0) return 0;
return ((num-1)%9+1);
}
};
Nim Game
class Solution {
public:
bool canWinNim(int n) {
return ((n%4)!=0);
}
};