I've tried while and for loops, but obviously it can't store the last digit since it's 0. So I'm wondering how I can make my program know the first digit is 0?
Thanks in advance!
I've tried while and for loops, but obviously it can't store the last digit since it's 0. So I'm wondering how I can make my program know the first digit is 0?
Thanks in advance!
It's not possible to store leading zeros of a user input in a numerical variable. You have to use a string to differ between input 001
and 01
:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string input;
std::cin >> input;
const auto numberOfZeros = std::count(std::begin(input), std::end(input), '0');
std::cout << "Zeros: " << numberOfZeros << '\n';
}
From a theoretical point of view you need to know:
00000 09080
).9080
has four).How can we do this programmatically? We just calculate the logarithm to the base of 10. If you know that the maximum number you can represent is limited, you can also perform a lookup.
Let's have a look at the lookup first (I'm not so good in C++, so syntax might vary a bit):
size_t numDigits(unsigned short myInt) {
if (myInt == 0) {
return 0;
} else if (myInt < 10) {
return 1;
} else if (myInt < 100) {
return 2;
} else if (myInt < 1000) {
return 3;
} else if (myInt < 10000) {
return 4;
} else { /* unsigned short cannot be larger than 65535 */
return 5;
}
}
To check whether your digit starts with a zero (with the maximum number of digits you are interested in) you just compare the number of digits with the number of maximum digits, e.g. 5 in your case:
bool hasLeadingZero(unsigned short myInt, size_t maxNumDigits) {
if (numDigits(myInt) < maxNumDigits) {
return true;
} else {
return false;
}
}
Now, you might not have a short
but maybe a higher number like int
or long
or even long long
and do not want to write all the comparisons in code. In this case, we can take the function that uses log10
from the linked stackoverflow question (I adjusted it a bit so that it's simpler to read for beginners, plus I changed the number of digits of 0 to 0, because in your situation it does not count as a digit):
size_t numDigits(unsigned i) {
if (i == 0) {
return 0;
} else {
return (size_t) log10 ((double) i) + 1;
}
}
This should work if I understand your question correctly. Maybe needs some code adjustments, because I just typed it in the text box here.