Click here to Skip to main content
15,905,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I want to make a function that recieves a number(positive integer) and returns 1 or 0. The rules are: It's okay to have 0 in the number, but if the number contains two or more 0s subsequently, then it doesn't satisfy the rules. Also, if the 0s are in the end of the number, then it doesn't satisfy the rule. If the rules are satisfied, the function returns 1, and if the rules aren't satisfied, it returns 0. For example, 12580302, 145829, 1040203 should return 1, and 123441, 1240012, 124040012, 124450 should return 0.

What I have tried:

I have no clue how to solve this so I haven't tried anything yet:(
Posted
Updated 22-Oct-20 2:37am

The first thing to do is to decide how you are going to analyse the number. On of the simplest ways is to use the modulus and divide operators to extract the remainder when dividing by 10. That way you can count the number of zero remainders, the number at the end, and the number of consecutive ones. So look at the documentation for the modulus and divide operators and have a think about how you could do it. Writing the steps on paper often makes things clearer.
 
Share this answer
 
If you aren't sure how to do something, try it manually first.
So take a number: 1240012 and think about how you would know that the function should return 0 or 1.

Simple: you look at the number, discard any trailing zeros, and then look for zeros in what is left. When you find one, you look at the next digit.
If that's a zero as well, you return 0.
If it isn't, remember you found one, and keep looking for zeros.
When you get to the end of the number, you check if you found any zeros at all and if so, return 1. Otherwise return 0.

That's pretty simple, isn't it? So now start thinking about ho to implement that in a function. Have a look here: If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^] and remember that in C you can extract the least significant digit with the modulus operator, and move all the other digits in an integer "down one place" with the divide operator.

Give it a try - it's pretty easy if you think about it for a few minutes.
 
Share this answer
 
v2
An alternative approach: convert the number into a string then search for the substring "00" in it (hint: there are standard C functions for such tasks), if the substring is not found then you've just to check for the trailing '0' in order to validate the number.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900