java中位移运算“<<“,“>>“,“>>>“
(1)"<<"为左移位运算
无论为正数还是负数,低位补0;
(2) “>>”为右移运算
如果为正数,则高位补0;
如果为负数,则高位补1;
(3) “>>>”为无符号右移运算
无论为正数还是负数,高位都补0;
二进制中1的个数
public class Solution {
public int NumberOf1(int n) {
int res=0;
for(int i=0;i<32;++i){ //注意位运算 & |
if((n & 1<
//特性n&(n−1),会将n的二进制中最低位由1变成0
public class Solution {
public int NumberOf1(int n) {
int res=0;
while (n!=0){
n&=(n-1);
++res;
}
return res;
}
}
幂运算
//直接计算
public class Solution {
public double Power(double base, int exponent) {
if(exponent<0){
base=1/base;
exponent=-exponent;
}
double res=1.0;
for(int i=0;i
public class Solution {
public double Power(double base, int exponent) {
if(exponent<0){
base=1/base;
exponent=-exponent;
}
return mypower(base,exponent);
}
public double mypower(double x,int y){
double res = 1;
while(y != 0){ //这里类似于分治
if((y & 1) != 0)
res *= x;
x *= x;
y = y >> 1;
}
return res;
}
}
字符串转数字(数字输出在[2^-32,2^32-1]之间)
import java.util.*;
public class Solution {
public static int StrToInt (String s) {
if(s==null && s.length()==0) return 0;
String string=s.trim();
if(string.length()==0) return 0;
boolean flag=true;
char numone=string.charAt(0);
long res=0; //注意这里是Long啊啊啊啊
if(!num(numone) && numone!='-' && numone!='+') return 0;
if(numone=='-') flag=false;
else if(numone=='+') flag=true;
else res=numone-'0';
for(int i=1;iInteger.MAX_VALUE) return Integer.MAX_VALUE;
if(!flag && res*(-1)='0' && c<='9')
return true;
else return false;
}
}



