malachite_nz/integer/logic/
checked_count_ones.rs

1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::integer::Integer;
10use malachite_base::num::logic::traits::CountOnes;
11
12impl Integer {
13    /// Counts the number of ones in the binary expansion of an [`Integer`]. If the [`Integer`] is
14    /// negative, then the number of ones is infinite, so `None` is returned.
15    ///
16    /// # Worst-case complexity
17    /// $T(n) = O(n)$
18    ///
19    /// $M(n) = O(1)$
20    ///
21    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
22    ///
23    /// # Examples
24    /// ```
25    /// use malachite_base::num::arithmetic::traits::Pow;
26    /// use malachite_base::num::basic::traits::Zero;
27    /// use malachite_nz::integer::Integer;
28    ///
29    /// assert_eq!(Integer::ZERO.checked_count_ones(), Some(0));
30    /// // 105 = 1101001b
31    /// assert_eq!(Integer::from(105).checked_count_ones(), Some(4));
32    /// assert_eq!(Integer::from(-105).checked_count_ones(), None);
33    /// // 10^12 = 1110100011010100101001010001000000000000b
34    /// assert_eq!(Integer::from(10u32).pow(12).checked_count_ones(), Some(13));
35    /// ```
36    pub fn checked_count_ones(&self) -> Option<u64> {
37        if self.sign {
38            Some(self.abs.count_ones())
39        } else {
40            None
41        }
42    }
43}