A special site for solving fun programming problems and challenges, interested in computer science, programming, basics, data structure and algorithms

 




Rahul loves to play with numbers, he challenges his friend Ankush with a problem related to numbers in which he has to first reverse the order of two digits and then swap them. Let us take the two digits as a and b.

Example 1:

Input:
a = 1234 
b = 67890
Output: 
9876 4321
Explanation: Reversing the given two numbers
will give: 4321 and 9876. After swapping it
would come as: 9876 and 4321.

Example 2:

Input:
a = 10000 
b = 3254
Output: 
4523 1

 

Your Task: Complete the two functions reverse_dig() and swap() with arguments as a and b references. Don't return anything to the function.

Constraints:
0 <= a, b <= 105


solution<1>:
// { Driver Code Starts
//Initial Template for C++

#include <iostream>
using namespace std;


// } Driver Code Ends
//User function Template for C++

void reverse_dig(int& a, int& b)
{
    //Add your code here.
    int num1 = 0, num2 = 0;
    while (a > 0)
    {
        int res = a % 10;
        num1 = num1 * 10 + res;
        a /= 10;
    }
    while (b > 0)
    {
        int res = b % 10;
        num2 = num2 * 10 + res;
        b /= 10;
    }
    a = num1;
    b = num2;
}
void swap(int& a, int& b)
{
    //Add your code here.
    int temp = a;
    a = b;
    b = temp;
}


// { Driver Code Starts.

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int a, b;
        cin >> a >> b;

        reverse_dig(a, b);
        swap(a, b);
        cout << a << " " << b << endl;
    }
    return 0;
}  // } Driver Code Ends
solution<2>:
void reverse_dig(int &a,int &b)
{
    //Add your code here.
    string a1,s1=to_string(a);   //to convert int to string.
    for(int i=s1.length()-1;i>=0;i--)
    {
        a1+=s1[i];
    }
    string a2,s2=to_string(b);
    for(int i=s2.length()-1;i>=0;i--)
    {
        a2+=s2[i];
    }
    a=stoi(a1);     //to convert string to int.
    b=stoi(a2);
    
}
void swap(int &a,int &b)
{
    //Add your code here.
    int temp=a;
    a=b;
    b=temp;
}

No comments:

Post a Comment