I'm trying to think of a function in C that would satisfy the following conditions:
- It accepts an integer greater than 0 as an argument;
- It rounds that integer up to the nearest value so that only the first digit is not a zero
For example:
53 comes out as 60..
197 comes out as 200..
4937 comes out as 5000..
Is there a way to do this so that the requirement is satisfied regardless of the number of trailing zeroes?
For example, I understand how I could do it in any individual case. divide 53 by 10 then ceil(), multiply by 10,
but I would like one that can handle any value.
Opinions? Ideas?
This should do it:
You can divide the number by ten until there is only one digit left, then multiply it back to size:
It's unnecessary to convert the number to a string and back. You can do this using basic modulo arithmetic and multiplication and division.
Here's a pure numeric solution, hopefully somewhat more efficient in terms of running time:
Logarithms are quite helpful here to provide a constant-time answer to the "how many zeros does this have?"
will take the logarithm base 10 and give you the number of zeros that will be in x.
You can then use the C occasional idiom
(A+B-1)/B
to quickly find the ceiling of A/B, which results in the correct leading digit in this way:
This is pseudocode but you should get the idea. The key understanding is that logarithms are the way to mathematically determine how many digits a number has.
By Cocoa APIs:
By Typical C style, mathematically:
I would convert the number to string. Get the length of the string.
Then: