/c++/Chapter 5/Question5_3.cpp

https://gitlab.com/0072016/ctci · C++ · 79 lines · 72 code · 4 blank · 3 comment · 13 complexity · 41b968a5dde1dcc87a45ff603bf55999 MD5 · raw file

  1. #include<iostream>
  2. #include<climits>
  3. #include<cmath>
  4. using namespace std;
  5. void printBinary(int n){
  6. int arr[32];
  7. int len = 8*sizeof(n);
  8. int mask = 1;
  9. int index = 0;
  10. while(len--){
  11. if(n&mask)
  12. arr[index] = 1;
  13. else
  14. arr[index] = 0;
  15. index++;
  16. mask <<= 1;
  17. }
  18. for(int i=31; i>=0; i--){
  19. cout<<arr[i];
  20. }
  21. cout<<'\n';
  22. }
  23. void next_smallest(int n){
  24. int len = 0;
  25. int tmp = n;
  26. int res;
  27. while(len<31){
  28. if((tmp&1) == 0){
  29. tmp >>= 1;
  30. len++;
  31. if(tmp&1 == 1){
  32. //10 occured
  33. res = n - (1<<len) + (1<<(len-1));
  34. printBinary(res);
  35. return;
  36. }
  37. }
  38. else{
  39. tmp >>=1;
  40. len++;
  41. }
  42. }
  43. //All 1's
  44. cout<<INT_MIN<<'\n';
  45. }
  46. void next_largest(int n){
  47. int len = 0;
  48. int tmp = n;
  49. int res;
  50. while(len<31){
  51. if(tmp&1 == 1){
  52. tmp >>= 1;
  53. len++;
  54. if((tmp&1) == 0){
  55. //01 occured
  56. res = n + (1<<len) - (1<<(len-1));
  57. printBinary(res);
  58. return;
  59. }
  60. }
  61. else{
  62. tmp >>=1;
  63. len++;
  64. }
  65. }
  66. cout<<INT_MAX;
  67. }
  68. int main(){
  69. int a = (1<<31)+(1<<29);
  70. cout<<a<<'\n';
  71. printBinary(a);
  72. next_smallest(a);
  73. next_largest(a);
  74. return 0;
  75. }