Reputation: 27
I'm trying to make a program where it asks the user to enter a number of 4 digits, and then the program will ready how many times the number "1" is repeated in the chosen digit. I have no idea how to make the program read the amount of 1's and then output the amount, any ideas please? Thank you.
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Ingrese un numero de 4 digitos porfavor. " << endl; //Enter a 4 digit number
cin >> num;
if (num > 999 & num < 10000) {
// count how many 1's the number has
} else {
cout << "El numero que usted ha ingresado no tiene unicamente 4 digitos." << endl; //The number you chose doesnt have only 4 digits. (more/less than)
}
}
Upvotes: 0
Views: 103
Reputation: 597245
A simple way would be to read the number as a std::string
instead of an int
(or at least convert the int
to std::string
with std::to_string()
), and then use std::count()
to count the '1'
characters.
if (num > 999 && num < 10000) {
std::string s = std::to_string(num);
int numOnes = std::count(s.begin(), s.end(), '1');
//...
}
Upvotes: 1
Reputation: 11
Simplest Way Of Doing
#include <iostream>
using namespace std;
int main()
{
int num, temp, rem, count = 0;
cout << "Enter 4 digit number:";
cin >> num;
temp = num;
while (temp != 0)
{
rem = temp % 10;
if (rem == 1)
{
count++;
}
temp = temp / 10;
}
cout << "The number of 1 in the four digit number " << num << " = " << count;
return 0;
}
Upvotes: 1
Reputation: 5409
Another approach is to continually divide the number by 10, and checking whether the last digit is 1:
int numOnes = 0;
int temp = num;
while (temp > 0) {
if (temp % 10 == 1) numOnes++;
temp = temp / 10;
}
Upvotes: 1