.....

....
Last edited on
you solve assignment step by step as it asks you:
1
2
//Replace each digit of abcd by ((digit + 7) mod
// 10). 

that would be something like:
/* unsigned int */ digit_A = (digit_A += 7) % 10 // and so on for each digit inside function

next step:
1
2
//Then looking at the number from the left, swap the first digit
// with the third 

as it says swap first digit with the third:

std::swap(digit_A, digit_B)

next:
//, swap the second digit with the fourth, std::swap(digit_B, digit_D)

return result:
1
2
//and return the
// new number. 

return new_digit_ABCD


the problem is that digit is a single digit consisting of 4 numbers, so you need to implement an algorithm to separate the digit into 4 parts, do math and swaps, and then assemble these digits back, and return that value.

there are several ways to do this.
one of them is to convert the digit into a stream and use std::peek to modify individual digits.

you could also implement a separate function which would translate the digit into a string, and from that point you can manipulate each character of a stream, and then reverse the process.

for example:
1
2
3
4
5
6
std::ostringstream temp;
temp << original_digit;
std::string string_digit = temp.str();
unsigned digit_A = string_digit.at(0) - '0'
unsigned digit_B = string_digit.at(1) - '0'
// etc.. 


you do the math and swaps and then reverse the process.
Your number comes in as an integer. It has 4 digits, so you can put those digits in an array, say
int a[4];

To find the digits one-by-one, the standard way is to use the modulo operator %: thus n%10 will always give you the last digit. You find each digit by looping 4 times, integer-dividing by 10 at the end of each loop: n /= 10;. This will reduce your number successively to three-, two, one-digit numbers. Each time you find a "last digit" put it in the array.

Then you can loop through each element of your array, adding 7 and then taking modulo 10.

Then do the two swaps with elements of your array.

Finally, reassemble a number from the individual digits in your array.


Take it one step at a time: e.g. check the elements of the array as you first find them, after you have done the add-7-and-modulo, after the swaps.


Topic archived. No new replies allowed.