Algorithms
Using base-10 logarithm
#include <math.h> typedef signed long long i64; int num_of_digits(i64 n){ i64 k = n < 0 ? -n : n; return log10(k) + 1; }
fn digits(mut n: u64) -> usize {let mut l = 1;while n >= 10 {n /= 10;l += 1;}l}- #include <math.h>
- typedef signed long long i64;
- int num_of_digits(i64 n){
- i64 k = n < 0 ? -n : n;
- return log10(k) + 1;
- }
#include <criterion/criterion.h> #include <stdlib.h> int num_of_digits(long long n); #define test(n, exp, name) Test(Basic_test, test##name) {cr_assert_eq(num_of_digits(n), exp);} test(1, 1, _1_one_d) test(10, 2, _2_two_d) test(12345, 5, _3_longer) test(9876543210, 10, _4_even_longer) test(9223372036854775807, 19, _5_the_longest) test(-20, 2, _6_negative) test(-7382956173, 10, _7_big_negative)
#[test]fn pow10() {assert_eq!(digits(0), 1);for i in 0..20 {assert_eq!(digits(POW10[i]), i+1);}assert_eq!(digits(std::u64::MAX), 20);}- #include <criterion/criterion.h>
- #include <stdlib.h>
#[test]fn pow10_minus_1() {for i in 1..20 {assert_eq!(digits(POW10[i] - 1), i);}}- int num_of_digits(long long n);
#[test]fn pow10_half() {for i in 1..20 {assert_eq!(digits(POW10[i] / 2), i);}}- #define test(n, exp, name) Test(Basic_test, test##name) {cr_assert_eq(num_of_digits(n), exp);}
- test(1, 1, _1_one_d)
- test(10, 2, _2_two_d)
- test(12345, 5, _3_longer)
- test(9876543210, 10, _4_even_longer)
- test(9223372036854775807, 19, _5_the_longest)
- test(-20, 2, _6_negative)
- test(-7382956173, 10, _7_big_negative)
Arithmetic Shift Right by n is equivalent to dividing by 2^n.