Created
November 11, 2012 01:23
-
-
Save kyrylo/4053280 to your computer and use it in GitHub Desktop.
Count digits in an integer number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # (1) | |
| # Meh. | |
| num = 6969 | |
| num.to_s.length #=> 4 | |
| # (2) | |
| # Hm... | |
| num = 6969 | |
| len = 0 | |
| begin | |
| len += 1 | |
| end while (num /= 10) > 0 | |
| p len #=> 4 | |
| # (3) | |
| # Ah!.. | |
| num = 6969 | |
| Math.log10(num).floor.succ #=> 4 | |
| # But... | |
| num = -6969 | |
| Math.log10(num).floor.succ #=> Math::DomainError: Numerical argument is out of domain - "log10" | |
| # Well. | |
| Math.log10(num.abs).floor.succ #=> 4 | |
| # Oh! | |
| num = 0 | |
| Math.log10(num).floor.succ #=> FloatDomainError: -Infinity | |
| # Mhm. | |
| Math.log10(num.zero? && 1 || num).floor.succ #=> 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment