时间限制:1秒空间限制:32768K热度指数:150911K
题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
这道题目很是喜欢只是我对位运算了解的甚少,所以这里只是 提供题目的解法。
【JAVA代码】
package Offer;
public class lertMove{
public static void main(String[] args) {
//使用n=10,二进制形式为1010,则1的个数为2;
int n = 8;
System.out.println(n + "的二进制中1的个数:" + Move(n));
}
public static int Move(int n) {
int count = 0;
while (n != 0) {
++count;
n = (n - 1) & n;
}
return count;
}
}
public class lertMove{
public static void main(String[] args) {
//使用n=10,二进制形式为1010,则1的个数为2;
int n = 8;
System.out.println(n + "的二进制中1的个数:" + Move(n));
}
public static int Move(int n) {
int count = 0;
while (n != 0) {
++count;
n = (n - 1) & n;
}
return count;
}
}
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
利用递归算法求解:
[JAVA代码,复制粘贴可用]
package Offer;
//递归
public class Power{
public static void main(String[] args) {
Power x=new Power();
System.out.print(x.Powerx(2,-3));
}
public double Powerx(double base, int exponent) {
int n=Math.abs(exponent);
if(exponent<0) {
base=1/base;
}
if(n==1) {
return base;
}
return base*Powerx(base,n-1);
}
}
//递归
public class Power{
public static void main(String[] args) {
Power x=new Power();
System.out.print(x.Powerx(2,-3));
}
public double Powerx(double base, int exponent) {
int n=Math.abs(exponent);
if(exponent<0) {
base=1/base;
}
if(n==1) {
return base;
}
return base*Powerx(base,n-1);
}
}