for 循环变量处理的基本理解
j ++
和++ j
什么区别
对于for (int j = 0; j < 10; j ++ )
和 for (int j = 0; j < 10; ++ j )
, j
的作用是相同的:就是把j
的值加上1
;对于赋值情况,z = ++ j
和 z = j ++
, 假设j = 0:
前者z = 1
, 后者z = 0
- 如果变量
j
在for
循环内部改变的话,会怎样?
for (int j = 0; j < 10; j ++ )
j = 4;
// 这种情况会出现死循环, TLE: 因为j ++ = 5 永远小于10, 会一直循环;
// int j = 0 指挥运行一次,之后就看for循环内部的j的变量,如果满足j < 10, 那么执行 j ++; 当j >= 10 时跳出循环;
// 所以并不是 一直是 j 从 0 ~ 9,要看for里面变量的改变和前面j++的部分结合;
- 例子
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int main()
{
for (int j = 0; j < 10; j ++ )
{
cout << "初始j:" << j << " ";
int k = j + 2;
cout << "k:" << k << " ";
int q = j ++;
cout << "q:" << q << " ";
// 考虑初始情况 j = 0
// 当前q = j,q = 0,但是j = j + 1, 这里j = 1
int z = ++ j;
cout << "z:" << z << " ";
//因为j已经是1, 这里z = j + 1, 所以z = 2
j = k - 1;
cout << "末尾j:" << j << " ";
cout << endl;
}
return 0;
}
- 结果
初始j:0 k:2 q:0 z:2 末尾j:1
初始j:2 k:4 q:2 z:4 末尾j:3
初始j:4 k:6 q:4 z:6 末尾j:5
初始j:6 k:8 q:6 z:8 末尾j:7
初始j:8 k:10 q:8 z:10 末尾j:9
- 例题
/*
* @lc app=leetcode id=38 lang=cpp
*
* [38] Count and Say
*
* https://leetcode.com/problems/count-and-say/description/
*
* algorithms
* Easy (41.40%)
* Likes: 888
* Dislikes: 6930
* Total Accepted: 312.9K
* Total Submissions: 750.8K
* Testcase Example: '1'
*
* The count-and-say sequence is the sequence of integers with the first five
* terms as following:
*
*
* 1. 1
* 2. 11
* 3. 21
* 4. 1211
* 5. 111221
*
*
* 1 is read off as "one 1" or 11.
* 11 is read off as "two 1s" or 21.
* 21 is read off as "one 2, then one 1" or 1211.
*
* Given an integer n where 1 ≤ n ≤ 30, generate the n^th term of the
* count-and-say sequence.
*
* Note: Each term of the sequence of integers will be represented as a
* string.
*
*
*
* Example 1:
*
*
* Input: 1
* Output: "1"
*
*
* Example 2:
*
*
* Input: 4
* Output: "1211"
*
*/
class Solution {
public:
//从前往后模拟做
string countAndSay(int n) {
string s = "1"; // n = 1 时
for (int i = 2; i <= n; i ++ ) // 从 n = 2 到 n
{
string new_s;
for (int j = 0; j < s.size(); j ++ )
{
int k = j; //从j开始寻找,判断后面有多少个相同字符
while (k < s.size() && s[k] == s[j]) k ++ ; //求出当前j对应的k值(k为相同字符的后一位标号)
new_s += to_string(k - j) + s[j];
//问题:这里不是从j = 0, 1, 2 ... 一直遍历吗, 那么new_s += 会出现多加的的情况
j = k - 1;
//cout << j << " ";
}
s = new_s;
}
return s;
}
};