Browse Source

feat: gray_code

Zhang Li 1 year ago
parent
commit
aa14d7b9de
2 changed files with 59 additions and 0 deletions
  1. 58 0
      src/solutions/other/gray_code.rs
  2. 1 0
      src/solutions/other/mod.rs

+ 58 - 0
src/solutions/other/gray_code.rs

@@ -0,0 +1,58 @@
+struct Solution;
+
+
+impl Solution {
+    pub fn gray_code(n: i32) -> Vec<i32> {
+        let count = i32::pow(2, n as u32) as usize;
+        let mut res = vec![0; count];
+        for i in 0..count {
+            let mut cur_num = 0;
+            for j in 0..n as usize {
+                let base = i32::pow(2, j as u32);
+                // 0,1
+                // 0,0,1,1
+                // 0,0,0,0,1,1,1,1
+                // 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1
+                let mut digit = if ((i as i32) / base) % 2 == 0 {
+                    0
+                } else {
+                    1
+                };
+                digit = if ((i as i32) / (base * 2)) % 2 == 0 {
+                    digit
+                } else {
+                    1 - digit
+                };
+                // println!("base: {}, digit: {}", base, digit);
+                cur_num += base * digit;
+            }
+            res[i] = cur_num;
+        }
+
+        res
+
+    }
+}
+
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_gray_code() {
+        let n = 2;
+        let res = Solution::gray_code(n);
+        assert_eq!(res, vec![0,1,3,2]);
+
+    }
+
+    #[test]
+    fn test_gray_code2() {
+        let n = 3;
+        let res = Solution::gray_code(n);
+        assert_eq!(res, vec![0,1,3,2,6,7,5,4]);
+
+    }
+}
+

+ 1 - 0
src/solutions/other/mod.rs

@@ -7,3 +7,4 @@ mod spiral_matrix;
 mod spiral_matrix_2;
 mod valid_number;
 mod set_matrix_zero;
+mod gray_code;