BotByte

Untitled

Aug 13th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. class Solution {
  2. public:
  3. string intToBinary(int n)
  4. {
  5. string str = "";
  6. while(n != 0){
  7. int digit = n%2;
  8. str += (char)(digit+'0');
  9. n = n/2;
  10. }
  11. reverse(str.begin(), str.end());
  12. return str;
  13. }
  14. int countDigitOne(int n) {
  15. if(n == 0) return 0;
  16. if(n == 1) return 1;
  17.  
  18. int pow2[25];
  19. pow2[0] = 1;
  20. for(int i=1; i<25; i++) pow2[i] = pow2[i-1] * 2;
  21.  
  22. int cntAllOne[25];
  23. cntAllOne[0] = 1;
  24. for(int i=1; i<25; i++) cntAllOne[i] = pow2[i-1] * i;
  25.  
  26. string str = intToBinary(n);
  27. int len = (int) str.length();
  28. int answer = 0;
  29.  
  30. int cumOneCount = 0;
  31. for(int i=0; i<str.length(); i++){
  32. if(str[i] == '0') continue;
  33.  
  34. int suffixLength = (int) str.length()-i-1;
  35. int countOfNumber = pow2[suffixLength];
  36. answer += cumOneCount*countOfNumber;
  37.  
  38. answer += cntAllOne[suffixLength];
  39. if(i != len-1) cumOneCount++;
  40. }
  41. answer += cumOneCount;
  42. return answer;
  43. }
  44. };
Advertisement
Add Comment
Please, Sign In to add comment