Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2023
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.56 KB | None | 0 0
  1. class Solution {
  2. private:
  3. unordered_map<int, int> hashMap;
  4.  
  5. public:
  6. int toBits(int n) {
  7. if (hashMap.count(n)) {
  8. return hashMap[n];
  9. }
  10.  
  11. int count = 0;
  12.  
  13. while (n > 0) {
  14. if (hashMap.count(n)) {
  15. count += hashMap[n];
  16. } else if (n % 2 == 1) {
  17. count += 1;
  18. }
  19.  
  20. n /= 2;
  21. }
  22.  
  23. return hashMap[n] = count;
  24. }
  25.  
  26. vector<int> countBits(int n) {
  27. vector<int> res(n + 1, 0);
  28.  
  29. for (auto i = 0; i < res.size(); ++i) {
  30. res[i] = toBits(i);
  31. }
  32.  
  33. return res;
  34. }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement