http://www.nowcoder.com/profile/454285/test/4003297/45188#summary
今天的计算机课上,老师给同学们出了一道题:
输入n个数,请将其中的偶数的二进制反转。eg:输入1 6 5
其中6是偶数,二进制表示为110,反转后为011,代表3,所以最终输出1 3 5.
小贱君最近脑子不怎么好使,想了半天也没想出来如何做,最后他向你寻求帮助了,帮帮可怜的小贱君吧!
#include <iostream>
using namespace std;
int flipNum(int x){
if (x & 1) return x; // x&1 为0 的时候说明x 为偶数,其他为奇数 对于“&” 位运算,只有1&1得1,其余为0
int n = 0;
cout << "xxxxx=" << x << endl;
while (x){
n = (n << 1) | (x & 1); // 翻转整数 二进制进行|位运算,只有0|0时候为0 ,其他为1
x = x >> 1;
cout << "nnnnnnnnnn = " <<n<< endl;
cout << "xxxxxxxxxx = " << x << endl;
}
return n;
}
int main(){
int N;
int x;
while (cin >> N){
for (int i = 0; i < N; ++i){
cin >> x;
cout << flipNum(x);
if (i != N - 1) cout << " ";
}
cout << endl;
}
}
//n << 1左移一位,相当于乘以2,右移 >> 相当于除以2, &是按位与
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace taotaoceshi
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入n个数字:");
string num = Console.ReadLine();
foreach (char item in num)
{
Console.Write(flipNum(int.Parse(item.ToString())));
}
Console.ReadKey();
}
static int flipNum(int x)
{
if ((x & 1) != 0)
{
return x;
}
int n = 0;
while(x != 0)
{
n = (x << 1) | (x & 1);
x = x >> 1;
}
return n;
}
}
}