Example:
Input: abcd
Output:dc
Input:abcde
Output:ed
Here's Code One. It works fine
#include <iostream>
#include <string>
int main(void) {
std::string str;
std::cin >> str;
std::string::size_type nstr = str.size();
std::string str2;
for (std::string::size_type
i = nstr - 1; i != ((nstr % 2 == 0) ? (nstr / 2 - 1) : (nstr / 2)); --i)
str2.push_back(str[i]);
std::cout << str2 << std::endl;
return 0;
}
|
Now I have modified the above code and get Code Two which also works fine.
#include <iostream>
#include <string>
int main(void) {
std::string str;
std::cin >> str;
std::string::size_type nstr = str.size();
std::string str2;
std::string::size_type nstr2 = (nstr % 2 == 0) ? (nstr / 2 - 1) : (nstr / 2);
for (std::string::size_type
i = nstr - 1; i != nstr2; --i)
str2.push_back(str[i]);
std::cout << str2 << std::endl;
return 0;
}
|
I guess the Code Two works faster than Code One because the nstr2 is calculated in advance before the loop.
Otherwise, (nstr % 2 == 0) ? (nstr / 2 - 1) : (nstr / 2) lc needs to be calculated in each loop.
Question: Is my guess correct ? And is it necessary in C++ pragramming?
https://stackoverflow.com/questions/3221577/what-is-a-loop-invariant
No comments:
Post a Comment