Home > Software engineering >  delete all digits except one
delete all digits except one

Time:01-01

I have this integer:

4732891432890432432094732089174839207894362154

It's big so I want to delete all digits in it except the digit 4 and I don't know how. This is my code:

#include <bits/stdc  .h>
using namespace std;
#define ll long long

int main()
{
   unsigned ll n, lastDigit, count = 0;
    ll t;
    cin >> t;
    while(t--)
    {
        cin >> n;

        while (n !=0)
        {
            lastDigit = n % 10;
            if(lastDigit == 4)
                count  ;
            n /= 10;
        }
        cout << count << "\n";
    }
     
    return 0;
}

I used the while loop because I have multiple test case not only that number.

CodePudding user response:

Just to show you current C (C 20) works a bit different then wat most (older) C material teaches you.

#include <algorithm>
#include <iostream>
#include <string>
#include <ranges>

bool is_not_four(const char digit)
{
    return digit != '4';
}

int main()
{
    // such a big number iwll not fit in any of the integer types 
    // needs to be stored in memory
    std::string big_number{ "4732891432890432432094732089174839207894362154" };

    // or input big_number from std::cin
    
    //  std::cout >> "input number : "
    //   std::cin >> big_number;
    
    // NEVER trust user input
    if (!std::any_of(big_number.begin(), big_number.end(), std::isdigit))
    {
        std::cout << "input should only contain digits";
    }
    else
    {
        // only loop over characters not equal to 4
        for (const char digit : big_number | std::views::filter(is_not_four))
        {
            std::cout << digit;
        }

        // you can also remove characters with std::remove_if
    }

    return 0;
}
  • Related