countDigits I need help
Hello I'm studying Computer Science and cant solve this problem right.
Write a method that counts how many times a specific digit a appears in the decimal representation of a number b.
It is guaranteed that the number b and the digit a are both greater than or equal to 0, with a being at most 9.
Even if b = 0, the method should correctly determine whether and how often the digit a appears.
My solution:
public static int countDigit(long a, int b) {
// counts how often the digit from b is contained in the number from l.
return (a == 0 && b == 0)
? 1
: (a == 0)
? 0
: (a % 10 == b ? 1 : 0) + countDigit(a / 10, b);
}
We have to solve this problem with a recursively defined method
Can anyone help me out ? ^^
7 Replies
⌛
This post has been reserved for your question.
Hey @Milan! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
I'll give u an example. The number 10023 contains 2 zeros. But my code does count 3 because the last modulo calculation is always 0. I dont know how to fix tha
That's an edge case, you need to kinda treat it as an exception.
Like, ensure your recursive call never call itself with a == 0. So if it starts with a == 0 that means that it was the initial call, and you treat it separately.
Note that "recursive" doesn't mean "not allowed to have more than 1 statements". Use if/else or possibly switches, for crying out loud
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.
Is it Java?
Yes it is but I already solved that problem but still thank you ^^
If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.