栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Code之位运算

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Code之位运算

 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;
    }
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022352.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号