231.Power of Two
题目要求判断一个数是否是2的乘方。
可以使用循环求解,也可以用位运算如下
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && ((n & (n-1)) == 0);
}
}
使用如下代码可以求解一个数的二进制中1的个数
int ans = 0;
while(x != 0){
++ans;
x = x&(x-1);
}
return ans;
405.Convert a Number to Hexadecimal
题目要求如下
Given an integer, write an algorithm to convert it to hexadecimal. For
negative integer, two’s complement method is used.Note:
All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal
string must not contain extra leading 0s. If the number is zero, it is
represented by a single zero character ‘0’; otherwise, the first
character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit
signed integer. You must not use any method provided by the library
which converts/formats the number to hex directly.
Example 1:Input: 26
Output: “1a”
Example 2:
Input:
-1Output: “ffffffff”
解法如下
public class Solution {
char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
public String toHex(int num) {
if(num==0){
return "0";
}
String result="";
while(num!=0){
result=map[(num&15)]+result;
num=num>>>4;//无符号右移
}
return result;
}
}
处理的过程就是每次获取最低4位,将其对应的16进制表示添加到结果字符串的开头。计算机里面就是二进制补码表示的,我们需要做的,就是把数字表示成32位二进制,然后每四位映射成一个16进制数字,最后去掉前导0。不需要考虑负数补码怎么实现。
延伸Power of Four与上题类似,要去掉2的乘方留下4的乘方
解法如下
public boolean isPowerOfFour(int num) {
return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
//0x55555555 十六进制数,是01010101010101010101010101010101
}