Lowest Bit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 15548 Accepted Submission(s): 11115
Problem Description
Given an positive integer A (1 <= A <= 100), output the lowest bit of A.
For example, given A = 26, we can write A in binary form as 11010, so the lowest bit of A is 10, so the output should be 2.
Another example goes like this: given A = 88, we can write A in binary form as 1011000, so the lowest bit of A is 1000, so the output should be 8.
Input
Each line of input contains only an integer A (1 <= A <= 100). A line containing “0” indicates the end of input, and this line is not a part of the input data.
Output
For each A in the input, output a line containing only its lowest bit.
Sample Input
26
88
0
Sample Output
2
8
这题比较水,直接的想法就是依次求转换成二进制,直至遇到了‘1’为止。下面我提供三种算法思想。
但是很多人会导致超时的算法,其原因是过于算法过于复杂和容易陷入死循环,下列是我自己写的一个代码超时
#include<iostream>
using namespace std;
int main(){
int A;
while((cin>>A)&&A){
int s=0; //余数
int k=1;
while(s!=1){ //遇到1之前进行求余 进位 判断等运算
A=A/2;
s=A%2;
k=k*2;
}
cout<<k<<endl;
}
}
没有超时的代码
#include<iostream>
using namespace std;
int main()
{
int time;
while(cin>>time) //持续输入
{
int i=2;
if(time==0)
exit(1); //表示程序异常退出
if(time%2==1) //如果数据最低位是1
cout<<"1"<<endl;
else{
while(1)
{
time=time/2; //求余
if(time%2==1) //求余运算为1,即为遇到了第一个1
{
cout<<i<<endl;
break;
}
i*=2; //添0进位
}
}
}
}
了解二进制的同学可以学习下列算法
1、按位异或运算
#include <iostream>
using namespace std;
int main(){
int n;
while(cin>>n && n!=0)
cout<<((n^(n-1))+1)/2<<endl;
return 0;
}
2、按位与运算
#include<iostream>
using namespace std;
int main()
{
int x;
while(cin>>x&&x!=0)
cout<<(x&-x)<<endl;
return 0;
}