Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool Badd( const char augend[], const char addend[], char sum[] )
- // IN IN OUT
- // Pre: augend and addend are strings representing valid binary numbers.
- // Post: sum is a string representing the sum of augend + addend.
- // Returns true if successful in addition, false otherwise.
- {
- // Temporary stub code. Return a string representing binary zero.
- //std::cout << "Adding:" << std::endl;
- char arrayOne[MAX_DIGITS+1];
- char arrayTwo[MAX_DIGITS+1];
- int augendStr = strlen(augend)-1;
- int addendStr = strlen(addend)-1;
- for (int i = 0; i < MAX_DIGITS+1; i++) {
- if (i > (MAX_DIGITS) - augendStr - 1) {
- arrayOne[i] = augend[MAX_DIGITS-i];
- }
- else {
- arrayOne[i] = '0';
- }
- }
- int j = 0;
- for (int i = 0; i < MAX_DIGITS; i++) {
- if (i > (MAX_DIGITS-1) - addendStr - 1) {
- arrayTwo[i] = addend[j];
- j++;
- }
- else {
- arrayTwo[i] = '0';
- }
- }
- j = 0;
- for (int i = 0; i < MAX_DIGITS; i++) {
- if (i > (MAX_DIGITS-1) - augendStr - 1) {
- arrayOne[i] = augend[j];
- j++;
- }
- else {
- arrayOne[i] = '0';
- }
- }
- for (int i = 0; i < MAX_DIGITS; i++) {
- //if (arrayOne[i] == NULL) {
- std::cout << arrayOne[i];
- //}
- }
- std::cout << std::endl;
- for (int i = 0; i < MAX_DIGITS; i++) {
- //if (arrayOne[i] == NULL) {
- std::cout << arrayTwo[i];
- //}
- }
- std::cout << std::endl << std::endl;
- bool carry = false;
- for (int i = MAX_DIGITS; i >= 0; i--) {
- bool carryin = carry;
- if (arrayOne[i] == '1' && arrayTwo[i] == '1') {
- if (carry) {
- sum[i] = '1';
- carry = true;
- }
- else {
- sum[i] = '0';
- carry = true;
- }
- }
- if ((arrayOne[i] == '1' && arrayTwo[i] == '0') || (arrayOne[i] == '0' && arrayTwo[i] == '1')) {
- if (carry) {
- sum[i] = '0';
- carry = true;
- }
- else {
- sum[i] = '1';
- carry = false;
- }
- }
- if ((arrayOne[i] == '0' && arrayTwo[i] == '0')) {
- if (carry) {
- sum[i] = '1';
- carry = false;
- }
- else {
- sum[i] = '0';
- carry = false;
- }
- }
- if (i == 0 && carryin != carry) {
- return false;
- }
- }
- sum[MAX_DIGITS] = '\0';
- return true;
- } // end Badd
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement