列表

详情


JAVA4. 交换变量值

描述

在不使用第三个变量的情况下交换两个int类型变量的值

输入描述

a变量和b变量的值

输出描述

交换后a变量和b变量的值,中间用空格隔开

示例1

输入:

1 2

输出:

2 1

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++ 解法, 执行用时: 3ms, 内存消耗: 384KB, 提交时间: 2021-10-30

#include<iostream>
using namespace std;
int main()
{
    int a,b;
    cin >> a >> b;
    a=a+b;
    b=a-b;
    a=a-b;
    cout << a << " " << b << endl;
    return 0;
}

C++ 解法, 执行用时: 3ms, 内存消耗: 524KB, 提交时间: 2022-03-31

#include <iostream>
using namespace std;

void swap(int &a, int &b)
{
    a = a + b;
    b = a - b;
    a = a - b;
}

void test01()
{
    //cout << "请输入两个整数:" << endl;

    int a, b;
    cin >> a >> b;

    swap(a, b);

    cout << a << " " << b << endl;

}

int main(void)
{
    test01();

    return 0;
}

Java 解法, 执行用时: 12ms, 内存消耗: 9352KB, 提交时间: 2022-07-29

import java.util.Scanner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
    public static void main(String[] args)throws IOException {
       BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
String[] sc=bu.readLine().split(" ");
        System.out.println(sc[1]+" "+sc[0]);
    }
}

Java 解法, 执行用时: 12ms, 内存消耗: 9436KB, 提交时间: 2022-07-14

import java.io.IOException;
import java.io.InputStream;


public class Main {
    public static void main(String[] args) throws IOException {
        InputStream in = System.in;
        byte[] buffer=new byte[30];
        in.read(buffer);
        int ofset = 0;
        int a = 0, b = 0;
        while (true) {
            if (buffer[ofset] == 32) {
                ofset++;
                break;
            }
            a = a * 10 + buffer[ofset] - 48;
            ofset++;
        }
        while (true) {
            if (buffer[ofset] == 10) {
                break;
            }
            b = b * 10 + buffer[ofset] - 48;
            ofset++;
        }

        a = a ^ b;
        b = a ^ b;
        a = a ^ b;

        System.out.println(a + " " + b);
    }
}

Java 解法, 执行用时: 12ms, 内存消耗: 9464KB, 提交时间: 2022-04-03

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        String[] line=br.readLine().split(" ");
        int a = Integer.valueOf(line[1]);
        int b = Integer.valueOf(line[0]);

        System.out.print(a+" "+b);

    }
}

上一题