Reputation: 1666
Someone please guide me how to check whether a specific digit exists in an integer
or not. for the sake of code optimization I am trying to avoid the use of strings
or any kind of loops
to iterate over all the digits
of the integer
.
If I need to find out whether 4
exists the in an integer or not, input and the output samples are given below:
Sample Input:
154
Sample Output:
true
Desired Code:
bool ifExists(int digit, int number)
{
if()
{
return true;
}
else
{
return false;
}
}
Possible Logic:
I believe there must be a mathematical approach which will do the job in the if
condition, however I am unable to find such method in cmath
library.
Upvotes: 0
Views: 825
Reputation: 1
A mathematical approach would be possible i think. By using log(x) in some crazy way.
But ones for surey you should use string or a loop by dividing by 10. log(x) requires far more resources than the way you want to use.
Also string or dividing by 10 is far more easy to read than a mathimatical solution.
For the mathimatical solution.
I suggest you try to transform the decimal number in a binary representation of it. Then it could be possible to create a filter for the digit you look for. By joining the filter and the transformed value through a bitwise & you could get what you seek. Im not sure if that realy is possible but that would be my first idea for an approach.
But as i said before. This method will be very expensive to the cpu and will be hard to read.
Upvotes: 0
Reputation: 25972
Convert integer to string, do a string search for digit.
The "mathematical" method would have to do the same, compute the digit sequence by division/remainder by 10 and compare with the given digit.
Upvotes: 4