fork(1) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. std::string encrypt(const std::string& word)
  5. {
  6. std::string result;
  7.  
  8. if (word.size()) // sanity check for empty string
  9. {
  10. std::size_t i = 0; // index of leftmost character
  11. std::size_t j = word.size() - 1; // index of rightmost character
  12.  
  13. while (i < j)
  14. {
  15. result += word[i++]; // You get the first character of the word
  16. result += word[j--]; // and then you get the last character
  17. }
  18.  
  19. if (i == j) // in some cases of words with an odd number of characters, only one character is left!
  20. result += word[i];
  21. }
  22.  
  23. return result;
  24. }
  25.  
  26. int main()
  27. {
  28. std::cout << encrypt("hacker") << '\n'; // even number of characters.
  29. std::cout << encrypt("phone") << '\n'; // odd number of characters.
  30. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
hraeck
pehno