How can I reverse last two digits of any number?

For example the number is 2345 I want to write a program which will print 2354 in output.

can u provide the link to the problem

#include <bits/stdc++.h>
using namespace std; 
#define max(a, b) (a < b ? b : a) 
#define min(a, b) ((a > b) ? b : a) 
#define mod 1e9 + 7 
#define FOR(a, c) for (int(a) = 0; (a) < (c); (a)++) 
#define FORL(a, b, c) for (int(a) = (b); (a) <= (c); (a)++) 
#define FORR(a, b, c) for (int(a) = (b); (a) >= (c); (a)--) 
#define INF 1000000000000000003 
typedef long long int ll; 
typedef vector<int> vi; 
typedef pair<int, int> pi; 
#define F first 
#define S second 
#define pb push_back 
#define POB pop_back 
#define MP make_pair 

  


int main() 
{ 
    ios::sync_with_stdio(0); 
    cin.tie(0);

		int n;
		cin>>n;
		string s=to_string(n);
		if(s.length()>=2)
		{
		swap(s[s.length()-1],s[s.length()-2]);
		}
		cout<<stoi(s)<<endl;
		
    
    return 0; 
} 
1 Like

Thanks for the reply, I don’t have the link to the question but I am writing the question down…

A boy asked his mother for M rupees in integer and using digits of M he created another integer N which is greater than M and the difference between M and N must be the least possible. Now help the his mother to find the integer N.

For example:
M= 2345
output will be 2354 (=N)
since the difference between M and N will be 9 which is least.

similarly if M =321
output will be 321(=N)
since in this case the difference between M and N will be 0 which is again the least possible difference.

okkk

@anon55646651 here is the sol.
#include
using namespace std;
int main()
{
int m,n,q,s=0;
cin>>m;
q=m/100;//Separates the integer from last 2 digits.
n=m%100;//Store the value last 2 digits.
while(n!=0)
{
s=s10+(n%10);//Reversing those 2 digits.
n/=10;
}
n=q
100+s;
cout<<n;

return 0;

}

1 Like

I don’t think that getting the last two digits of the number will bring you the next greater number.
For example: M = 2354 then according to your last two digit swap rule, N will be 2345
but N should be greater M.
So your approach is wrong of finding the next bigger number by swapping last two digits.
next greater number

1 Like

how can be 321 greater than 321?

1 Like

If you like to do it with python you may see this.

n=input()
print(n.replace(n[-2:], n[-2:][::-1]))
1 Like