Skip to content

Commit 0c2a59b

Browse files
Merge pull request #6 from rvguradiya/add-generate_gray_code_n_bits
Added problem statement for generating Gray code for n bits
2 parents 35da9f9 + 9a869db commit 0c2a59b

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
This problem was asked by **Apple**.
2+
3+
[Gray code](https://en.wikipedia.org/wiki/Gray_code) is a binary code where each successive value differ in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions.
4+
5+
Given a number of bits `n`, generate a possible gray code for it.
6+
7+
For example, for `n = 2`, one gray code would be `[00, 01, 11, 10]`.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
public class Approach {
2+
public static void generateGrayCode(int n, int bit, String str) {
3+
if (n == 1) {
4+
System.err.println(str + bit);
5+
bit = bit == 1 ? 0 : 1;
6+
System.err.println(str + bit);
7+
return;
8+
}
9+
generateGrayCode(n - 1, 0, str + bit);
10+
bit = bit == 1 ? 0 : 1;
11+
generateGrayCode(n - 1, 1, str + bit);
12+
}
13+
14+
public static void main(String[] args) {
15+
generateGrayCode(4, 0, "");
16+
}
17+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function generateGrayCode(n, bit = 0, s = "") {
2+
if (n == 1) {
3+
console.log(s + bit);
4+
bit = bit == 1 ? 0 : 1;
5+
console.log(s + bit);
6+
return;
7+
}
8+
generateGrayCode(n - 1, 0, s + bit);
9+
bit = bit == 1 ? 0 : 1;
10+
generateGrayCode(n - 1, 1, s + bit);
11+
}
12+
13+
generateGrayCode(4);
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
def generateGrayCode(n,bit=0,s=''):
2+
3+
if n == 1:
4+
print(s + str(bit))
5+
bit = 0 if bit ==1 else 1
6+
print(s + str(bit))
7+
return;
8+
9+
generateGrayCode(n-1,0,s+str(bit))
10+
bit = 0 if bit ==1 else 1
11+
generateGrayCode(n-1,1,s+str(bit))
12+
13+
generateGrayCode(4)

0 commit comments

Comments
 (0)