Varun Alur
Varun Alur

Reputation: 11

How to use a string array to breakdown the individual digits of a number?

I have to write a code which takes an input and prints out a new number made up of primes that are present in the original number. ex. input: 453 Output: 53 I have already written the code:

#include <iostream>
#include<string>

using namespace std;

int main()
{
    int number;
    int digit;
    int reverse = 0;
    int reverse1;
    int digit1;
    cout<<"input a number"<<endl;
    cin>>number;
    int flag = 0;

    while(number!=0)
    {
        digit = number % 10;
        number = number / 10;
        for(int i = 2; i < digit; i++)
        {
            if(digit % i == 0)
            {
                flag = 1;
            }
        }
        if(flag == 0)
        {
            reverse = reverse * 10 + digit;
        }
    }

    reverse1 = reverse;
    while(reverse1 != 0)
    {
        digit1 = reverse1 % 10;
        reverse1 = reverse1 / 10;
        cout<<digit1;
    }

    cout<<endl;
}

Whats a better way to generate the same output , but shorter code. I have just started to learn programming , so please provide easy to understand solutions :)

Upvotes: 1

Views: 64

Answers (1)

mattnewport
mattnewport

Reputation: 14057

If I understand what you're trying to do correctly (effectively remove digits other than 2, 3, 5 & 7 from your input number) then this should work:

#include <algorithm>
#include <iostream>
#include <set>
#include <string>

using namespace std;

int main() {
    const set<int> primes{2, 3, 5, 7};
    string num;
    cin >> num;
    num.erase(remove_if(begin(num), end(num), [&](char c){ return !primes.count(c - '0'); }), end(num));
    cout << num << '\n';
}

There's no error checking for valid number inputs but that's easily added if you need it. Live version.

Upvotes: 2

Related Questions