当前位置:网站首页>*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
边栏推荐
猜你喜欢
随机推荐
实现H5网页授权
*2-4 每日温度 *2-5 接雨水
RHCE Course Summary
小程序模板制作流程,小程序模板制作方便快捷
汇编语言学习(八)
*5-2 CCF 2014-12-3 集合竞价
【LeetCode】1413. 逐步求和得到正数的最小值
小程序程序开发怎么做?应以突出功能为主
Talking about CQRS Mode
C语言中常用的数组排序方法:冒泡排序、选择排序、插入排序、数组的移动(含代码详解)以及相关联系题
Shell course summary
Analysis of SEATA Distributed Transaction Framework
Thinking about oracle financial data authority
String为什么是不可变的?
* 2-2 OJ 1163 missile interception of beta
[Video coding learning] - understanding of transformation
*1-5 OJ 642 俄式乘法
Add-apt-repository command details
RHCE课程总结
C语言 三子棋(含完整 代码详解)









