This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Like it and see. Make it a habit. Wechat search [a coding] follow this programmer who is struggling in the Internet.

This article is included in the technical expert training, which contains my learning route, series of articles, interview question bank, self-study materials, e-books, etc. Welcome to star ⭐ ️

Topic describes

Difficulty: Easy

Use an if statement to sort the values of a, B, and C from smallest to largest

knowledge

  • ifjudge
  • Two Numbers exchange

Their thinking

1. If judgment

Compare – > exchange.

If, as a branch structure, is used to do different subsequent processing according to different judgment conditions.

2. Switch two numbers

The usual practice, like exchanging two cups of water, is to find an empty cup first, which is a temporary variable to store the value. The code is as follows:

int t=a;
a=b; 
b=t;
Copy the code

Advanced practice, how to do without using other variables? Think 🤔 and give the answer at the end of the article.

Code implementation

/** * order the values of a, b, and c in ascending order */
public class question_04 {
    public static void main(String args[]){
        int a=9,b=5,c=7,t;
        if(a>b) {
            t=a; a=b; b=t;
        }
        if(a>c) {
            t=a; a=c; c=t;
        }
        if(b>c) {
            t=b; b=c; c=t;
        }
        System.out.println("a="+a+",b="+b+",c="+c); }}Copy the code

The output

conclusion

How can I exchange the values of two numbers without using other variables?

A, add/multiply the two numbers. I’m subtracting/dividing. The code is as follows:

a=a*b;
b=a/b; // is equivalent to a*b/b=a, that is, a is assigned to B
a=a/b; // this is equivalent to a*b/a=b, i.e. b is assigned to A
Copy the code

I’ll leave it to you to add and subtract.

Finally, if the article is helpful to you.

Remember to give the article a thumbs up!

Welcome to have a look, share big factory interview and algorithm brush questions, look forward to becoming friends with you.