【Leetcode】:89. Gray Code 问题 in JAVA
来源:互联网 发布:淘宝教学视频教程全集 编辑:程序博客网 时间:2024/06/05 05:27
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]
. Its gray code sequence is:
00-0 01-1 10-2 11-3
这道题目要求计算格雷码,输出对应的十进制数字,难度为中等,不过实现起来还是很简单的。
public class Solution { public List<Integer> grayCode(int n) { if (n == 0) { List<Integer> list = new ArrayList<Integer>(); list.add(0); return list; } if (n == 1) { List<Integer> list = new ArrayList<Integer>(); list.add(0); list.add(1); return list; } List<Integer> grayM = grayCode(n - 1); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < Math.pow(2,n); i++) { if (i < Math.pow(2, n-1)) { //前面一半的数字不变 list.add(grayM.get(i)); } else { //后面一半的数字反向排列,再在前面添加一个‘1’ int res = grayM.get( (int)Math.pow(2, n) - i - 1 ) + (int)Math.pow(2, n - 1); list.add(res); } } return list; }}
0 0
- 【Leetcode】:89. Gray Code 问题 in JAVA
- 【leetcode】89. Gray Code【java】
- [LeetCode] 89. Gray Code java
- [Leetcode] Gray Code (Java)
- [LeetCode][Java] Gray Code
- [LeetCode]89.Gray Code
- LeetCode 89. Gray Code
- [Leetcode] 89. Gray Code
- LeetCode --- 89. Gray Code
- [leetcode] 89.Gray Code
- 89. Gray Code LeetCode
- [LeetCode]89. Gray Code
- Leetcode 89. Gray Code
- [leetcode] 89. Gray Code
- LeetCode *** 89. Gray Code
- [LeetCode]89. Gray Code
- leetcode 89. Gray Code
- leetcode 89. Gray Code
- iOS 视图的tag使用详解
- vs2005与sql server2005的安装顺序是什么?
- 使用 Spring Data JPA 简化 JPA 开发
- ubuntu错误--Could not get lock /var/lib/dpkg/lock
- entity framework 6 自己编写的通用数据类
- 【Leetcode】:89. Gray Code 问题 in JAVA
- mathtype中常用设置
- 解决:Adb connection Error:远程主机强迫关闭了一个现有的连接
- Android应用的LinearLayout中嵌套RelativeLayout的布局用法
- 常用的SQL语法
- VS2015崩溃问题;devenv.exe[5736]中发生未处理的Microsoft .NET Framework异常
- C字符串和C++字符串的区别
- Redis 3.0 源码注释
- IIS7伪静态web.config配置的方法和规则