Java Software Programming Examples For Beginners / Interview: How To Swap Integer (and String) Variables Without Using a Temporary Variable Java программирование примеры для начинающих / интервью: Как поменять целое (и string) переменных без использования временной переменной
Say x & y are the integer variables. Скажем х и у являются переменными целое. The challenge is to swap them without using a temporary variable. Задача состоит в том, чтобы их без подкачки, используя временную переменную.
The solution is as simple as the problem itself: Решение же просто, как сама проблема:
x = x + y; х = х + у;
y = x - y; у = х - год;
x = x - y; х = х - год;
Update 1: Jack and Alexey pointed out a typo in my solution which has since been corrected. Update 1: Джек и Алексей отметил, опечатка в моем решение, которое с тех пор была исправлена. Please see their comments below. Просьба свои замечания см. ниже.
The simplicity of the solution appeals to me. Простота решения обращается ко мне. It clearly demonstrates the meaning of assignment operator ( “=” ). Он ясно показывает смысл уступки оператора ( "=").
What if they are Strings? Что делать, если они струнах?
Note: You can use String methods in Java API. Примечание: Вы можете использовать методы String в Java API.
Here is the solution: Вот решение:
x = x + y; х = х + у;
y = x.substring(0, x.indexOf(y)); у = x.substring (0, x.indexOf (у));
x = x.substring(x.indexOf(y) + y.length()); х = x.substring (x.indexOf (г) + y.length ());
Can you see the similarity? Можете ли вы видите сходства?
Can you provide a simpler solution to either of the above? Можете ли вы представить простое решение для любой из выше?
Update 2: Robert just did (see his comment below). Update 2: Роберт только что сделал (см. его комментарий ниже). He pointed out that the String solution doesn’t work when one string is contained in another. Он указал на то, что String решение не работает, когда одна строка содержится в другом. His solution is: Его решение заключается в следующем:
x = x + y; х = х + у;
y = x.substring(0, x.length() - y.length()); у = x.substring (0, x.length () - y.length ());
x = x.substring(y.length()); х = x.substring (y.length ());
Filed under Поданного в соответствии с How To Как , Java Software Программное обеспечение Java , Tech Note Технология Примечание | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | это статья |
Email this Article Отослать Статья
You may also like to read Вы можете также люблю читать |




October 30th, 2005 at 2:53 am 30 октября 2005 года в 2:53 утра
x : 1 y : 2 х: 1 год: 2
x = x + y; х = х + у;
x : 3 y : 2 х: у 3: 2
x = x - y; х = х - год;
x : 1 y : 2 х: 1 год: 2
y = x - y; у = х - год;
x : 1 y : -1 х: 1 год: -1
October 30th, 2005 at 3:04 am 30 октября 2005 года в 3:04 утра
x = x+y; х = х + у;
y = xy; у = абв;
x = xy; х = абв;
October 30th, 2005 at 8:36 am 30 октября 2005 года в 8:36 утра
Maybe Может быть
x = x + y; х = х + у;
y = x - y; у = х - год;
x = x - y; х = х - год;
October 30th, 2005 at 9:24 am 30 октября 2005 года в 9:24 утра
@Jack & Alexey @ Джека и Алексей
Oops! Секундочку!
Thanks for the catch. Спасибо за уловом. Corrected. Исправлено.
Just checking if you are attentive Просто проверка, если вы внимательны
October 30th, 2005 at 9:25 am 30 октября 2005 года в 9:25 утра
BTW: I actually asked this question today while interviewing candidates. BTW: Я действительно просил этот вопрос сегодня во время собеседований с кандидатами.
October 31st, 2005 at 8:15 am 31 октября 2005 года в 8:15 утра
The string sample will fail if the string x contains the string y. Строка выборки не удастся, если строка х содержит строку г. For example, Например,
String x = “Hello World”; String х = "Здравствуй, мир";
String y = “Hello”; String у = "Hello";
Step 1: x = x + y; Шаг 1: х = х + у;
x = “Hello WorldHello” х = "Hello WorldHello"
Step 2: y = x.substring(0, x.indexOf(y)); Шаг 2: у = x.substring (0, x.indexOf (у));
x.indexOf(y) = 0, so y = “”; x.indexOf (г) = 0, поэтому у = "";
Step 3: x = x.substring(x.indexOf(y) + y.length()); Шаг 3: х = x.substring (x.indexOf (г) + y.length ());
x.indexOf(y) = 0 and y.length = 0, so x = “Hello WorldHello” x.indexOf (г) = 0 и y.length = 0, поэтому х = "Hello WorldHello"
You can fix this by using lastIndexOf() method in String like Вы можете исправить это с помощью lastIndexOf () метод в строки типа
x = x + y; х = х + у;
y = x.substring(0, x.lastIndexOf(y)); у = x.substring (0, x.lastIndexOf (у));
x = x.substring(x.indexOf(y) + y.length()); х = x.substring (x.indexOf (г) + y.length ());
or you could eliminate the indexOf() calculations altogether and just use the lengths of the strings или вы могли бы ликвидировать indexOf () расчеты и вообще просто использовать длин струн
x = x + y; х = х + у;
y = x.substring(0, x.length() - y.length()); у = x.substring (0, x.length () - y.length ());
x = x.substring(y.length()); х = x.substring (y.length ());
October 31st, 2005 at 8:53 am 31 октября 2005 года в 8:53 утра
@Robert @ Роберта
I like that. Мне нравится это. It looks cleaner. Она выглядит более чистой.
November 9th, 2005 at 2:08 am 9 ноября 2005 года в 2:08 утра
Unfortunately, the code to exchange integer values will fail for values that cause over- or underflow. К сожалению, код для обмена целые значения будут обречены на ценностях, которые вызывают более или underflow.
However, you can use exclusive-or (xor), which is like add without carry. Тем не менее, вы можете использовать исключительные-либо (xor), который хотел добавить, без перевозки. The following unobvious code exchanges all int values. Unobvious следующий код обмена int всех ценностей.
x = x ^ y;х = х у ^;y = x ^ y;у = х у ^;x = x ^ y;х = х у ^;September 28th, 2006 at 6:10 am 28 сентября 2006 года в 6:10 утра
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? им кодирования анаграмма игры слов к съемным письма от одного знака к другому (до вниз), используя threeBottons класса, каким образом я должна использовать строку и символ-код? (the second character of label one should place to the second character of label two) i need that much help thanks (второй символ знака нужно место для второй символ знака два) я, что многое нужно помочь спасибо
November 29th, 2007 at 8:30 am 29 ноября 2007 года в 8:30 утра
import java.io.*; импорт java.io. *;
class ab класс ab
{ (
public static void main(String arg[]) throws IOException государственной статической силы основных (String аргумент []) броски IOException
{ (
int x=6; int х = 6;
if(x=6) если (х = 6)
{ (
System.out.println(”Hi…”); System.out.println ( "Hi…");
} )
} )
} )
the question is .. Вопрос .. Is it possible to run this program with out changing if(x=6) Можно ли запустить эту программу без изменения, если (х = 6)
February 26th, 2008 at 4:34 am 26 февраля 2008 года в 4:34 утра
if(x > y) если (х> у)
{ (
x = x- y; х = х-у;
y = y + x; у = у + х;
x = y - x; х = у - х;
} )
else еще
{ (
y = y - x; у = у - х;
x = x + y; х = х + у;
y = x - y; у = х - год;
} )