fork download
  1. #include <string>
  2. #include <cstdlib>
  3.  
  4. long firstDigitToEnd(long n) {
  5. bool neg = (n < 0); // Preserve signed-ness.
  6. if (neg) { n = labs(n); } // Obtain absolute value, for convenience.
  7.  
  8. std::string num = std::to_string(n); // Convert number to string.
  9.  
  10. char first = num[0]; // Obtain first digit.
  11. num.erase(0, 1); // Erase first digit, shift rest forwards.
  12. num.push_back(first); // Append first digit to end.
  13.  
  14. // And we're done. Convert string back to number, restore signed-ness.
  15. return (neg ? -(std::stol(num)) : std::stol(num));
  16. }
  17.  
  18. // -----
  19.  
  20. // Testing code.
  21.  
  22. #include <iostream>
  23. #include <limits>
  24.  
  25. void readCin(long& l);
  26.  
  27. int main() {
  28. long n = 0;
  29.  
  30. do {
  31. if (n) {
  32. std::cout << "Result: " << firstDigitToEnd(n) << std::endl;
  33. }
  34.  
  35. std::cout << "Input number, or 0 to exit: ";
  36. readCin(n);
  37. } while (n);
  38.  
  39. std::cout << "...And we're gone." << std::endl;
  40. }
  41.  
  42. // Read a number, or clear the buffer if non-number is entered.
  43. void readCin(long& l) {
  44. using std::cin;
  45.  
  46. cin >> l;
  47. cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  48.  
  49. if (cin.fail()) {
  50. cin.clear();
  51. cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  52. l = 0;
  53. }
  54. }
Success #stdin #stdout 0s 3476KB
stdin
123456789
-123456789
999999998
-999999998
0
stdout
Input number, or 0 to exit: Result: 234567891
Input number, or 0 to exit: Result: -234567891
Input number, or 0 to exit: Result: 999999989
Input number, or 0 to exit: Result: -999999989
Input number, or 0 to exit: ...And we're gone.