LeetCode题目 Gray Code 的解法与疑问
2014-06-28 13:29
483 查看
LeetCode Gray Code 这一题,不是难题不过有个地方没搞清楚。
https://oj.leetcode.com/problems/gray-code/
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
gray code sequence is:
我写的答案是这样的:
vector<int> grayCode(int n)
{
vector<int> Bits(1,0);
for(int GrayDigit = 0;GrayDigit<n;GrayDigit++)
{
int count = Bits.size();
while(count!=0)
Bits.push_back(Bits[--count]|(1<<GrayDigit));
/*
vector<int>::iterator iter = Bits.end();
while(Bits.begin()!=iter) //push之后再做while循环会报错
Bits.push_back(*(--iter)|(1<<GrayDigit));*/
}
return Bits;
}
在计算每一位的方法中,过程用int标记(int count = Bits.size();)没有任何问题。
不明白为什么用迭代器却不行:vector<int>::iterator iter = Bits.end();
第一次进入while循环是正确的,可以成功push_back, 之后Bits中有 0,1两个元素。然是回到while循环判断那里就会报错,难道push之后iter不能再和Bits这个容器对比??
https://oj.leetcode.com/problems/gray-code/
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:
我写的答案是这样的:
vector<int> grayCode(int n)
{
vector<int> Bits(1,0);
for(int GrayDigit = 0;GrayDigit<n;GrayDigit++)
{
int count = Bits.size();
while(count!=0)
Bits.push_back(Bits[--count]|(1<<GrayDigit));
/*
vector<int>::iterator iter = Bits.end();
while(Bits.begin()!=iter) //push之后再做while循环会报错
Bits.push_back(*(--iter)|(1<<GrayDigit));*/
}
return Bits;
}
在计算每一位的方法中,过程用int标记(int count = Bits.size();)没有任何问题。
不明白为什么用迭代器却不行:vector<int>::iterator iter = Bits.end();
第一次进入while循环是正确的,可以成功push_back, 之后Bits中有 0,1两个元素。然是回到while循环判断那里就会报错,难道push之后iter不能再和Bits这个容器对比??
相关文章推荐
- leetcode题目: Reverse Integer 的C语言解法
- leetcode题目 寻找和为SUM的两数(O(nlogn)和O(n)解法)
- LeetCode Online Judge 题目C# 练习 - Gray Code
- leetcode题目: Find the Difference 的C语言解法
- leetcode经典题目及解法记录
- LeetCode Swap Nodes in Pairs题目的一种简洁解法
- [leetcode.com]算法题目 - Gray Code
- leetcode题目: Sort Characters By Frequency 的C语言解法
- LeetCode 题目答案 Largest Rectangle in Histogram 极品解法的解释
- leetcode题目 全排列(三种解法)
- 【LeetCode】89. Gray Code解法及注释
- LeetCode题目:String to Integer (atoi)
- LeetCode Happy Number高效解法
- Leetcode006:ZigZag Conversion的Java解法
- 买股票题目一种很好的通用解法
- leetcode题目:Reorder List
- leetcode题目:Linked List Cycle和Linked List Cycle II
- leetcode题目解答报告(1)
- leetcode[Repeated Substring Pattern]//待整理多种解法
- 【Leetcode】:89. Gray Code 问题 in JAVA