how to reverse a number in c++ code example

Example 1: reversing numbers in C++

#include <iostream>
#include <string>

using namespace std;

int reverse(int number); // reverses the number's digits

int main() {

	int x = 18475;

	cout << "18475 reversed is " << reverse(18475) << endl;
}

int reverse(int number) {

	int result = 0;

	while (number > 0) {
		result = result * 10 + number % 10;
		number /= 10;
	}

	return result;
	
}

Example 2: c++ reverse array

int arr[5] = {1, 2, 3, 4, 5}; //Initialize array

for(int i = 0; i < size(arr); i++) {
	//Create temporary variable to hold current value in array
	int temp = arr[i];
	//Set the current value in the array to the mirrored value in array
	arr[i] = arr[size(arr) - 1 - i];
	//Set mirrored value in array to temp, swapping the two numbers
	arr[size(arr) - 1 - i] = temp;
}

Example 3: reverse() in c++

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
    vector<int>a = {11,22,33,44,99,55};
    reverse(a.begin(), a.end());
    auto it = a.begin();
    for(it= a.begin(); it!=a.end(); it++){
        cout << *it << ' ';    
    }
}

Example 4: reverse c++

reverse(str.begin(),str.end());

Example 5: print reverse number

void printReverse(int n) {
  if (n < 1) return;
  cout << n << endl;
  printReverse(n - 1);
}

printReverse(10);  /// 10 9 8 7 6 5 4 3 2 1

Tags:

Java Example