89. Gray Code - LeetCode Solution | C++ | Go | Kotlin | Java | JS | TS | Python
raunit - in LeetcodeExplore the Gray Code problem on LeetCode with comprehensive solutions and explanations in various programming languages. Perfect for coding enthusiasts!
class Solution {
public:
vector<int> grayCode(int n) {
vector<int>ans;
for(int i = 0; i<pow(2,n); i++){
ans.push_back(i ^ (i>>1));
}
return ans;
}
};
func grayCode(n int) []int {
// type length capacity
res := make([]int, 0, (1<<n))
for i := 0; i < (1 << n); i++ {
res = append(res, i^(i>>1))
}
return res
}
class Solution {
fun grayCode(n: Int): List<Int> {
var res = mutableListOf<Int>()
// kotlin do not have << or >> or ^
for (i in 0 until (1 shl n)) {
res.add(i xor (i shr 1));
}
return res;
}
}
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<>();
int size = (1<<n);
for(int i = 0; i<size; i++){
res.add(i ^ (i >> 1));
}
return res;
}
}
/**
* @param {number} n
* @return {number[]}
*/
var grayCode = function(n) {
let res = [];
for(let i = 0; i<(1<<n); i++){
res.push(i^(i>>1));
}
return res;
};
function grayCode(n: number): number[] {
let res : number[] = [];
for(let i = 0; i<(1<<n); i++){
res.push(i^(i>>1));
}
return res;
};
class Solution:
def grayCode(self, n: int) -> List[int]:
return [i^(i>>1) for i in range(2**n)]
Tagsleetcodemediumc++dsamath
raunit
Technical Writer at CodingKaro
Share this on