Friday, 10 February 2017

How swap first and last digit of an integer ?

#include<iostream>
#include<string>

using namespace std;
int main()
{
 int num;
 cout << "Enter the number" << endl;
 cin >> num;
 int digit=0;
 int g = num;
 while (g != 0) {
  g /= 10;
  digit++;
 }
 int *arr;
 g = num;
 int index = 0;
 arr = new int[digit];
 for (int i = 0; i < digit; ++i) {
  arr[index++] = g % 10;
  g /= 10;
 }
 g = num;
 int first=0;
 int last = 0;
 g = num;
 for (int i = 1; i <= digit; ++i) {
  if (i == 1) {
   for (int i = 0; i < digit; ++i) {
    first = g % 10;
    g /= 10;
   }
  }
  if (i == digit) {
   last = num % 10;
  }
} int newn = last;
 for (int i = digit-2; i>0; --i) {
  if (i != digit && i != 0) {
   newn = arr[i] + newn * 10;
  }
 }
 newn *= 10;
 newn += first;
 cout << newn << endl;
 system("pause");
    return 0;
}

No comments:

Post a Comment