Click here to Skip to main content
15,065,914 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
See more:
for example lets say i have an integer like 345. i want to write a function that will accept the integer which i can do, and return 354.i know i can extract the last digit 5 with a modolus operator(%) but then i need to swap the value with 4 and place 4 in the last position which i can do.But after all this,i dont know how to put at all the numbers back and return the completed integer which is 354.plz help me.It is an assignment for school.
Posted

Why not give a hint:

You know how to get the last digit by modulo.

How much is 345 / 10 (all values integer, including the result!)? If you don't know the answers debug it. And after that think again what you already know about modulo.

And so on and on and on for the other digits.

And after swapping the right digits recalculate your number d1 + d2 *10 + d3 *100 + .... Of course you will do that in a loop.

Regards.
   
v2
that might work for a number like 354 0r 454,but what about bigger numbers like 3456 0r 4567.iam really confused????
   
Comments
[no name] 2-Jul-12 9:22am
   
Do not post questions as answers. You can add comments.

Think about something like this:
int myNumber= 19372625;
while (myNumber > 0)
{
currentDigit= myNumber % 10;
// here put current digit to an array
....
// Prepare for next digit. you can write this shorter: myNumber/= 10;
myNumber= myNumber / 10;
}

After this you have the array of digits of your original number. Pay attention in which order you will have it.
Now you go throug this array until you find the two digits to swap. As soon you found it break the loop.
And then recalculate.

That's all I will tell you. Otherwhise you will not learn what you have to learn.
Regards
brian 3 2-Jul-12 10:29am
   
sorry i meant to say..i have figured out how to this...but iam been trying to modify the program in such a way that when a user enters a specified number like 345 or 2398 in the main portion of the program,the function that u have given me above will just perform the specified operation of returning the largest number still using the same digits of the number supplied by the user.
[no name] 2-Jul-12 15:48pm
   
You missed the comment "// here put current digit to an array" .... That is your job to solve ;)
Eugen Podsypalnikov 2-Jul-12 9:58am
   
// but what about bigger numbers like 3456 0r 4567

Very c00l ! Nearly all digits are the same ! 5ed :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900