zoukankan      html  css  js  c++  java
  • 进制转换

    1)进行进制转换之前首先需要明白”进制“的概念,首先N进制的数字元素取值范围是0~N-1,即N进制中有N个数字元素,另外,就是“进制”中的“位”的概念,N进制下一个数字序列(N进制形式),序列中每个位上的数字乘以这个位对应的数值,然后累加,就得出这个N进制数对应的十进制形式。N进制下,从低位到高位(从左到右),第i的位表示的数值是N^i(i从0开始)。参考:https://www.zhihu.com/question/20993504

    2)

    输入一个十进制的正整数,从低位开始查找,找到第一个置位(1)比特的位置
    按照如下规则对正整数进行置位比特的查找:
    1. 当查找失败时,比如输入正整数0,返回-1
    2. 当查找成功时,返回该比特的位置
    例子:
    比如 如入12,二进制表示是0000000000001100,则第一个置位比特为2

    代码实现:

    import java.util.Scanner;
    public class Main {
    public static void main(String[] args){
    int bitIndex=bitSearch();
    System.out.println(bitIndex);
    }
    public static int bitSearch(){
        
        Scanner scanner=new Scanner(System.in);
        boolean is=scanner.hasNextInt();//32位位的int型最大值是10位(2147483647),当输入的数值超过这个范围时,is就是false。
        if (is) {
            int inputValue=scanner.nextInt();
            scanner.close();
            if (inputValue<0) {
                inputValue*=-1;
            }
                int index=0;
                while(inputValue!=0){
                    if (inputValue%2==1) {
                        return index;
                    }
                    else {
                        inputValue/=2;
                        index++;
                    }
                }
                return -1;
        }
        else{
            return -1;
        }    
    }
    }

       代码也可以获得负整数的置位比特位置,因为负数在计算机中是以补码的形式存储的,正数也是补码形式存储的,只不过整数的补码就是其原码本身,而补码就是由此负数对应正数的原码取反,再加一得到,并且,这样的话,其实负数的补码中置位比特位置就是负数对应的正数的置位比特位置。

  • 相关阅读:
    LeetCode 121. Best Time to Buy and Sell Stock
    LeetCode 221. Maximal Square
    LeetCode 152. Maximum Product Subarray
    LeetCode 53. Maximum Subarray
    LeetCode 91. Decode Ways
    LeetCode 64. Minimum Path Sum
    LeetCode 264. Ugly Number II
    LeetCode 263. Ugly Number
    LeetCode 50. Pow(x, n)
    LeetCode 279. Perfect Squares
  • 原文地址:https://www.cnblogs.com/lz3018/p/5328638.html
Copyright © 2011-2022 走看看