2021-01-26HDOJ_Lowest_Bit

挺水的,但也学到了简单方法
题目如下:
Lowest Bit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4212 Accepted Submission(s): 2790

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

我的解法((虽然也用了位运算但并未简化多少)

#include <iostream>
#include <cmath>
using namespace std;
//刚学c++,先适应适应,还不会基本的语法
int main()
{
	int A;
	scanf("%d",&A);
	while (A)
	{
		int m = 0,power = 0;
		while (m!=1)
		{
			m = A&1;//与1就能提取出最后一位二进制码
			A = A>>1;//右移一位的意思
			power++;//权重
		}
		cout << pow(2,power-1) << endl;
		scanf("%d",&A);
	}
	return 0;
}

交上ac以后,我又搜索了CSDN上的更好的方法
1.

include<cstdio>
int main()
{
	int a,m;
	while(scanf("%d",&a),a)
	{
		for(int i=0;i<10;i++)
		{
			if(a&(1<<i))
			//意思是1后边跟i个零
			//如果这个式子为真就代表10...0是所求
			{
				m=1<<i;//妙,依然用二进制求m
				break;
			}
		}
		printf("%d\n",m);//输出自然转成十进制
	}
	return 0;
}

2.

#include<stdio.h>
int main()
{
    int A;
    while(scanf("%d",&A)&&A!=0)
    {
          printf("%d\n",A&(-A));
    }
    return 0;
}//我直呼牛逼!!!机器用补码储存负数.
posted @   弦合二挂  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示