Java Software Programming Examples For Beginners / Interview: How To Swap Integer (and String) Variables Without Using a Temporary Variable Exemplos programação Java Software para principiantes / Entrevista: Como a swap inteiro (ea corda) sem usar variáveis uma variável temporária
Say x & y are the integer variables. Dize x & y são as variáveis do tipo inteiro. The challenge is to swap them without using a temporary variable. O desafio é o de swap-los sem utilizar uma variável temporária.
The solution is as simple as the problem itself: A solução é simples como o problema em si:
x = x + y; x = x + y;
y = x - y; y = x - y;
x = x - y; x = x - y;
Update 1: Jack and Alexey pointed out a typo in my solution which has since been corrected. Update 1: Jack e Alexey apontam para um erro na minha solução que já foi corrigido. Please see their comments below. Por favor, veja abaixo as suas observações.
The simplicity of the solution appeals to me. A simplicidade da solução agrada-me. It clearly demonstrates the meaning of assignment operator ( “=” ). Ela demonstra claramente o significado da atribuição operador ( "=").
What if they are Strings? E se eles são Strings?
Note: You can use String methods in Java API. Nota: Você pode usar métodos String em Java API.
Here is the solution: Aqui está a solução:
x = x + y; x = x + y;
y = x.substring(0, x.indexOf(y)); y = x.substring (0, x.indexOf (y));
x = x.substring(x.indexOf(y) + y.length()); x = x.substring (x.indexOf (y) + y.length ());
Can you see the similarity? Você pode ver a semelhança?
Can you provide a simpler solution to either of the above? Vocês podem fornecer uma solução mais simples para qualquer um dos acima?
Update 2: Robert just did (see his comment below). Update 2: Robert fez (ver seu comentário abaixo). He pointed out that the String solution doesn’t work when one string is contained in another. Ele salientou que a solução String não funciona quando uma string está contida no outro. His solution is: Sua solução é:
x = x + y; x = x + y;
y = x.substring(0, x.length() - y.length()); y = x.substring (0, x.length () - y.length ());
x = x.substring(y.length()); x = x.substring (y.length ());
Filed under Arquivado em How To How To , De Java Software Java Software , De Tech Note Nota Tech | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | este artigo |
Email this Article E-mail este artigo
You may also like to read Você pode também gosta de ler |





October 30th, 2005 at 2:53 am Outubro 30o, 2005 em 2:53 am
x : 1 y : 2 x: y 1: 2
x = x + y; x = x + y;
x : 3 y : 2 x: y 3: 2
x = x - y; x = x - y;
x : 1 y : 2 x: y 1: 2
y = x - y; y = x - y;
x : 1 y : -1 x: y 1: -1
October 30th, 2005 at 3:04 am Outubro 30o, 2005 em 3:04 am
x = x+y; x = x + y;
y = xy; y = xy;
x = xy; x = xy;
October 30th, 2005 at 8:36 am Outubro 30o, 2005 em 8:36 am
Maybe Talvez
x = x + y; x = x + y;
y = x - y; y = x - y;
x = x - y; x = x - y;
October 30th, 2005 at 9:24 am Outubro 30o, 2005 em 9:24 am
@Jack & Alexey Jack & @ Alexey
Oops! Opa!
Thanks for the catch. Agradecimentos para a captura. Corrected. Corrigido.
Just checking if you are attentive Basta verificar se você está atento
October 30th, 2005 at 9:25 am Outubro 30o, 2005 em 9:25 am
BTW: I actually asked this question today while interviewing candidates. BTW: Eu realmente esta pergunta hoje entrevistar os candidatos ao mesmo tempo.
October 31st, 2005 at 8:15 am Outubro 31o, 2005 em 8:15 am
The string sample will fail if the string x contains the string y. A corda amostra irá falhar se a corda ao string contém x y. For example, Por exemplo,
String x = “Hello World”; String x = "Olá Mundo";
String y = “Hello”; String y = "Olá";
Step 1: x = x + y; Etapa 1: x = x + y;
x = “Hello WorldHello” x = "Olá WorldHello"
Step 2: y = x.substring(0, x.indexOf(y)); Etapa 2: y = x.substring (0, x.indexOf (y));
x.indexOf(y) = 0, so y = “”; x.indexOf (y) = 0, então y = "";
Step 3: x = x.substring(x.indexOf(y) + y.length()); Etapa 3: x = x.substring (x.indexOf (y) + y.length ());
x.indexOf(y) = 0 and y.length = 0, so x = “Hello WorldHello” x.indexOf (y) = 0 e y.length = 0, então x = "Olá WorldHello"
You can fix this by using lastIndexOf() method in String like Você pode corrigir esse problema usando lastIndexOf () como método de String
x = x + y; x = x + y;
y = x.substring(0, x.lastIndexOf(y)); y = x.substring (0, x.lastIndexOf (y));
x = x.substring(x.indexOf(y) + y.length()); x = x.substring (x.indexOf (y) + y.length ());
or you could eliminate the indexOf() calculations altogether and just use the lengths of the strings ou você poderia eliminar o indexOf () cálculos por completo e só usar os comprimentos das cordas
x = x + y; x = x + y;
y = x.substring(0, x.length() - y.length()); y = x.substring (0, x.length () - y.length ());
x = x.substring(y.length()); x = x.substring (y.length ());
October 31st, 2005 at 8:53 am Outubro 31o, 2005 em 8:53 am
@Robert Robert @
I like that. Eu gosto disso. It looks cleaner. Parece-se mais limpo.
November 9th, 2005 at 2:08 am 9 de novembro de 2005, às 2:08 am
Unfortunately, the code to exchange integer values will fail for values that cause over- or underflow. Infelizmente, o código para o intercâmbio de valores inteiros irá falhar por valores que causam mais-ou underflow.
However, you can use exclusive-or (xor), which is like add without carry. No entanto, você pode usá-ou exclusivo (XOR), que é como acrescentar, sem proceder. The following unobvious code exchanges all int values. Os seguintes unobvious código intercâmbios todos os int valores.
x = x ^ y;x = x ^ y;y = x ^ y;y = x ^ y;x = x ^ y;x = x ^ y;September 28th, 2006 at 6:10 am 28 de setembro de 2006 em 6:10 am
im coding a anagram word game to swap letters from one label to another (up to the down) by using a threeBottons class how should i use the string and char code? im codifica um anagrama palavra o jogo de cartas swap de um rótulo para outro (até o baixo) pelo uso de uma classe threeBottons Como devo usar a string e char código? (the second character of label one should place to the second character of label two) i need that much help thanks (o segundo personagem de um rótulo deve colocar-se à segunda personagem de rótulo dois) eu necessito que ajudam muito obrigado
November 29th, 2007 at 8:30 am 29 de novembro de 2007 às 8:30 am
import java.io.*; importação java.io. *;
class ab classe AB
{ (
public static void main(String arg[]) throws IOException public static void main (String arg []) throws IOException
{ (
int x=6; int x = 6;
if(x=6) if (x = 6)
{ (
System.out.println(”Hi…”); System.out.println ( "Olá…");
} )
} )
} )
the question is .. a questão é a .. Is it possible to run this program with out changing if(x=6) É possível executar este programa a se mudar para fora (x = 6)
February 26th, 2008 at 4:34 am 26 de fevereiro de 2008, 4:34 am
if(x > y) if (x> y)
{ (
x = x- y; x = x-y;
y = y + x; y = x + y;
x = y - x; x = y - x;
} )
else diferente
{ (
y = y - x; y = y - x;
x = x + y; x = x + y;
y = x - y; y = x - y;
} )