当前位置:网站首页>*1-4 OJ 605 Gray Code
*1-4 OJ 605 Gray Code
2022-08-09 14:51:00 【Ye Xiaobai】
题目描述



输入

输出

样例输入

样例输出

源代码
方法1
#include<iostream>
#include <bitset>
using namespace std;
int D2G(int x)
{
return x ^ (x >> 1);
}
int main()
{
int x;
cin >> x;
int y=D2G(x);
int i, j = 0;
int a[1000];
i = y;
while (i)
{
a[j] = i % 2;
i /= 2;
j++;
}
for (i = j - 1; i >= 0; i--)
cout << a[i];
cout << endl;
}
方法2
#include <stdio.h>
#include <string.h>
#include<iostream>
#include<stack>
using namespace std;
int main()
{
int n;
stack<int>q;
while (cin >> n)
{
int a[10000];
int k = 0;
int t = n;
while (t > 0)
{
q.push(t % 2);
t /= 2;
}
while (!q.empty())
{
a[k++] = q.top();
q.pop();
}
cout << a[0];
for (int i = 1; i < k; i++)
{
if (a[i - 1] == a[i])
{
cout << '0';
}
else
{
cout << '1';
}
}
cout << endl;
}
return 0;
}
关于这题
第一种解题方法 较为简单 The first method is explained here
Implementation of Gray Code 有很多办法 But in fact there are only two operations,就能产生:one is right shift 一个是异或 这里都用D2G 函数来实现了
This time we gety 已经是 Gray code for decimal digits We just need to convert it to binary
异或 ^
In fact, it can be regarded as non-carrying2进制加法 (Or summed up as the same0 不同为1)
1^0 1
0^1 1
0^0 0
1^1 0
边栏推荐
猜你喜欢
随机推荐
*5-1 CCF 2015-03-1 图像旋转
【视频编码学习】——变换的理解
Badge of openharmony container components
How to develop small programs?should focus on features
C语言 最大公约数,最小公倍数(详细注释代码 一次解决)
汇编语言学习(八)
shell课程总结
Shell course summary
*1-2 OJ 190 run-length code
What are the steps website small program development?
dpkg: error: cannot new file '/var/lib/dpkg/info/format-new': no
元气森林“0糖”背后的百亿推手
C语言 一维数组和二维数组的定义及使用
*2-1 OJ 254 翻煎饼
汇编语言学习(三)
[Video coding learning] - SAD and SATD
RHCE课程总结
Which applet making software is easy to use?how to choose?
RHCE课程总结
idea安装









