mardi 5 mars 2019

Remove one digit at a time from an integer in C++

I have a program where i have to remove one digit from a number at a time, append the given digit to the least significant of the result and find smallest.

Given number and digit:
123 2

Expected result:
122 //3 is removed
132 //2 is removed
232 //1 is removed
The answer is: 122 //Smallest of the three
//In all cases append 2 to least significant place.

This is what i tried but it's not working. Please help! //t is number of test cases.

Main Function:

int main()
{
    int t;
    cin>>t; //no. of test cases
    while(t--)
    {
        long long int n,d;
        cin>>n>>d; // n is number and d is digit to be appended
        long long int answer=n; // Initial answer
        long long int result;
        //Know the length of the number
        string n_temp=to_string(n); //
        int n_length=n_temp.length();
        cout<<"The number length is "<<n_length<<endl;
       //Send the digit no and assign the value to result 
        for(int i=0; i<n_length; i++) {
            result=0;
            result=removeDecimal(n,i);
            result=result*10+d;
            cout<<"Result is: "<<result<<endl;
            //Compare result with answer for the smallest
            if(result<answer) {
                answer=result;
            }
        }

        cout<<answer<<endl;
    }

    return 0;
}

removeDecimal function:

long long int removeDecimal(long long int number, long long int digit_no) {
     long long int result = number;
     long long int decimal = (int)pow(10,digit_no); //10's power required
     long long int div = number/decimal; 
     if(div>0) {
        long long int right_digits = number % decimal; //Get right digits
        result = div/10; // Get left digits
        result *= 10*decimal;
        result = result + right_digits;
     }
     cout<<"The number after removal is: "<<result<<endl;
     return result;
   }

Aucun commentaire:

Enregistrer un commentaire