Advertisement
Guest User

Untitled

a guest
Mar 24th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. bool Badd( const char augend[], const char addend[], char sum[] )
  2. // IN IN OUT
  3. // Pre: augend and addend are strings representing valid binary numbers.
  4. // Post: sum is a string representing the sum of augend + addend.
  5. // Returns true if successful in addition, false otherwise.
  6. {
  7. // Temporary stub code. Return a string representing binary zero.
  8. //std::cout << "Adding:" << std::endl;
  9. char arrayOne[MAX_DIGITS+1];
  10. char arrayTwo[MAX_DIGITS+1];
  11.  
  12. int augendStr = strlen(augend)-1;
  13. int addendStr = strlen(addend)-1;
  14.  
  15. for (int i = 0; i < MAX_DIGITS+1; i++) {
  16. if (i > (MAX_DIGITS) - augendStr - 1) {
  17. arrayOne[i] = augend[MAX_DIGITS-i];
  18. }
  19. else {
  20. arrayOne[i] = '0';
  21. }
  22.  
  23. }
  24. int j = 0;
  25. for (int i = 0; i < MAX_DIGITS; i++) {
  26. if (i > (MAX_DIGITS-1) - addendStr - 1) {
  27. arrayTwo[i] = addend[j];
  28. j++;
  29. }
  30. else {
  31. arrayTwo[i] = '0';
  32. }
  33.  
  34. }
  35.  
  36. j = 0;
  37. for (int i = 0; i < MAX_DIGITS; i++) {
  38. if (i > (MAX_DIGITS-1) - augendStr - 1) {
  39. arrayOne[i] = augend[j];
  40. j++;
  41. }
  42. else {
  43. arrayOne[i] = '0';
  44. }
  45.  
  46. }
  47.  
  48. for (int i = 0; i < MAX_DIGITS; i++) {
  49. //if (arrayOne[i] == NULL) {
  50.  
  51. std::cout << arrayOne[i];
  52. //}
  53. }
  54. std::cout << std::endl;
  55. for (int i = 0; i < MAX_DIGITS; i++) {
  56. //if (arrayOne[i] == NULL) {
  57.  
  58. std::cout << arrayTwo[i];
  59. //}
  60. }
  61. std::cout << std::endl << std::endl;
  62.  
  63. bool carry = false;
  64. for (int i = MAX_DIGITS; i >= 0; i--) {
  65. bool carryin = carry;
  66. if (arrayOne[i] == '1' && arrayTwo[i] == '1') {
  67. if (carry) {
  68. sum[i] = '1';
  69. carry = true;
  70. }
  71. else {
  72. sum[i] = '0';
  73. carry = true;
  74. }
  75. }
  76. if ((arrayOne[i] == '1' && arrayTwo[i] == '0') || (arrayOne[i] == '0' && arrayTwo[i] == '1')) {
  77. if (carry) {
  78. sum[i] = '0';
  79. carry = true;
  80. }
  81. else {
  82. sum[i] = '1';
  83. carry = false;
  84. }
  85. }
  86. if ((arrayOne[i] == '0' && arrayTwo[i] == '0')) {
  87. if (carry) {
  88. sum[i] = '1';
  89. carry = false;
  90. }
  91. else {
  92. sum[i] = '0';
  93. carry = false;
  94. }
  95. }
  96. if (i == 0 && carryin != carry) {
  97. return false;
  98. }
  99. }
  100. sum[MAX_DIGITS] = '\0';
  101. return true;
  102. } // end Badd
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement