A clever solution to reverse the string
For example, the requirement is to reverse the string. Of course there are many methods, which I think are quite interesting. ^_^
#include
#include
using namespace std;int main() { string s; cin>>s; for(int i = s.size(); i--; ) { cout<
Input: abcOutput: cba
This code is characterized I ?? I put it in the judgment statement. At first I was not very understandable, but I exited the loop when I was equal to 0 according to the output. This speculation was confirmed by a breakpoint test.
To prove this conjecture, I continued to write two short sections of code.
#include #include using namespace std;int main() { string s; cin >> s; for (int i = s.size(), j = s.size() - 1; i--, j--;) { cout << s[i] << " " << s[j]; } cout << endl; return 0;}
Input: abcOutput: c bb a
The final status is:
i=1, j=0
Another piece of code is:
#include #include using namespace std;int main() { string s; cin >> s; for (int i = s.size(), j = s.size() - 1; j--, i--;) { cout << s[i] << " " << s[j]; } cout << endl; return 0;}
Input: abcOutput: c bb a (program crashes after this part is output)
The final status is:
j=-1, i=0
The first code indicates that there is a return value for the auto-subtraction operation, and it is the value of this variable. Why does j continue to be reduced after j is reduced to 0 in the second code, the reason for the decrease is that the loop is still going, And the loop is not exited because the result of the comma operator here is the last one.
I am not very clear about the small details, because it is rarely used in the actual code word, that is, it is determined that it is stopped because of 0. What about negative numbers? That is to say, whether the direct type conversion of negative numbers is true or false.
#include using namespace std;int main() { if(-1) cout<<"t"; else cout<<"f"; return 0;}
Output: t
Then I tried again in C #. Here I can't automatically convert int to bool, so I have to write a method.
class Program{ static void Main(string[] args) { string s; s = Console.ReadLine(); for (int i = s.Length; isBool(i--);) { Console.Write(s[i]); } Console.WriteLine(); } static bool isBool(int n) { if (n > 0) return true; else return false; }}
Input: abcOutput: cba
All in all, well, I admit it is Easy, but the process is full of fun. I like this feeling of hypothetical exploration. Bye ......