2013-04-10 81 views
7

在Java中是否有內置函數可用於交換兩位?如何交換Java中的兩位整數?

例如:

_ _ _ _ 1 _ _ 0位3交換,第0和成爲_ _ _ _ 0 _ _ 1

我知道它可以使用的長程序來完成按位操作,但我想避免這樣做。

+0

你要多久它不是?我不認爲有一個內置的專門交換位。 – iamnotmaynard 2013-04-10 14:24:11

+0

不存在這樣的功能 – BlackJoker 2013-04-10 14:26:21

+2

「按位操作的長程序」是要走的路,儘管它可能不會那麼長。 – 2013-04-10 14:29:05

回答

5

我做它的細節,但你可以加入它變成單行

int temp1 = (i & 0x1) << 3; //extract lowest bit #1 and place at pos# 4 
int temp2 = (i & 0x8) >> 3; //extract bit #4 and place at pos #1 
i = (i & temp1) | (i & ~temp1); //now pos #4 is ready  
i = (i & temp2) | (i & ~temp2); //now pos #1 is ready 
7

這裏是另一種方式,稱爲三角洲交換。

int t = (i^(i >> 3)) & 1; 
return i^t^(t << 3); 

或者更一般地說:

static int swap(int x, int i, int j) 
{ 
    // precondition: i > j 
    int d = i - j; 
    int y = (x^(x >> d)) & (1 << j); 
    return x^y^(y << d); 
} 
10

您也可以嘗試這種方式

//positions are indexed from 0 and in order ...[4][3][2][1][0] 
//so changing 3 and 1 will make    ...[4][1][2][3][0] 
public static int swap(int i, int pos1, int pos2) { 

    int bit1 = (i >> pos1) & 1;// bit at pos1 
    int bit2 = (i >> pos2) & 1;// bit at pos2 

    if (bit1 == bit2) 
     return i; // no need to swap since we change 1 with 1 or 0 with 0 

    // Since we are here it means that we need to change 1->0 and 0->1. 
    // To do this we can use XOR (^). 
    // Lets create mask 000001010 with ones at specified positions 
    int mask = (1 << pos1) | (1 << pos2); 

    return i^mask;// TADAM!!! 
}