地址:1680. 连接连续二进制数字

结果:AC

代码:

  1. class Solution {
  2. public:
  3. int concatenatedBinary(int n) {
  4. const int max = 1000000007;
  5. string str;
  6. int ans = 0;
  7. char num[32];
  8. int i = 1;
  9. while(i<=n){
  10. int sheft = 31;
  11. while( (i & (1<<sheft)) == 0) sheft--;
  12. while(sheft >= 0){
  13. if((i & (1<<sheft)) == 0)
  14. str.push_back('0');
  15. else
  16. str.push_back('1');
  17. sheft--;
  18. }
  19. i++;
  20. }
  21. for(int j = 0;j<str.size();j++){
  22. ans = (ans * 2 + (str[j] - '0')) % max;
  23. }
  24. return ans;
  25. }
  26. };