We have discussed different approaches to swap two integers without the temporary variable. How would you swap variables in a single statement without using library function?
Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write “x, y = y, x”.
Pretty ugly, but this should do the trick..
int x = 100;
int y = 19;
x = y + -x + (y = x);
Outputs:
19,100
100,19
You can use bitwise xor
x = x ^ y ^ (y = x);
// Java program to swap two variables in single line
class GFG
{
public static void main (String[] args)
{
int x = 5, y = 10;
x = x ^ y ^ (y = x);
System.out.println("After Swapping values of x and y are "
+ x + " " + y);
}
}
Related
Say I have the following variables:
int x = 1;
int y = 2;
//some calculations follow(x and y stay the same init values) that somehow require you to interchange the values of y and x
how can I set y = 1 and x = 2 in one line of code??
Not sure why that's necessary, but you can do it like:
int x = 2, y = 1;
Try using bitwise XOR(^) operator.
x = x ^ y ^ (y = x);
Your completed code may look like,
class Main
{
public static void main (String[] args)
{
int x = 1, y = 2;
x = x ^ y ^ (y = x);
System.out.println("x after swapping:\nx="+x+"\ny after swapping,\ny="+y);
}
}
The following code is designed to factorize a number typed into the variable x.
public class testMod{
public static void main(String[]args){
double x = 11868681080091051216000;
StringBuilder output = new StringBuilder("1 * ");
for(double y = 2; y <= x; y++){
while (x % y == 0) {
System.out.print("Calculating... \n");
String printNumber = y + " * ";
x = x / y;
output.append(printNumber);
System.out.print(output.substring(0, output.length() - 2) + "\n");
}
}
}
}
The problem is that the compiler treats 11868681080091051216000 as an int, regardless of the attempt to assign it to a double. As such, it's out of range.
To specify a double literal, you can simply append D to the end – but do note that you'll lose precision this way:
double x = 11868681080091051216000D;
System.out.println(x); // prints 186868108009105E22
If you need the full precision, you can use a BigInteger instead, but you'll still need to specify that number in expressions that Java can handle, such as a product of its factors.
I have been struggling with an exercise in the Java Headfirst book( CH5: p121 for reference). It's a loop inside another loop which adds/substracts some values from instance variables.
Input:
x = x + 3
Outputs:
x= 54 y = 6
public class MixFor5 {
public static void main(String[] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer++) {
for (int inner = 4; inner > 1; inner--) {
x = x + 3;
y = y - 2;
if (x == 6) {
break;
}
x = x + 3;
}
y = y - 2;
}
System.out.println(x + " " + y);
}
}
My result is when doing it by myself with a notepad is x=42 y = 8 because then both loop conditions are met. What am i doing wrong? where did I go wrong in my thoughtprocess?
these are my notes -> pastebin note
I have not tried debugging first because I want to figure this by myself first so that I don't make the same mistakes in the future.
Thanks in advance,
tvanderv
if(x == 6) will never get true. The reason behind this is,
When inner = 4
x = x + 3 executes two times i.e. means x = 6.
then, inner = 3
now first x = x + 3 (before if(x == 3) condition) will give output x = 9. So x > 6 it will not break loop.
You did this step wrong in your notes.
Please someone explain the ("x = " + x) part of the code.
public class While-With-Nested-If {
public static void main(String [] args) {
int x = 1;
while(x < 100) {
System.out.println("x = " + x);
if(x % 2 == 0) {
x++;
} else {
x *= 2;
}
}
}
}
In this case the operator is used to concatenate a string with the string representation of x.
It depends on the operand type.
For String type operands it creates a new String instance (String objects are immutable) and assigns to it the concatenation of two operands.
For numeric types it works as addition operator.
In this case, it concatenates a String with the string representation of x. For example: x = 42;
The "+" operator acts as syntactic sugar for the concatenation operator in regards to String operations.
It is used to concatenate the two strings in your case.
When you write
String a = b + c + d;
then it gets converted into:
String a = new StringBuilder(b).append(c).append(d).toString();
You may refer Oracle docs for more details
In this code block while loop will iterate till x is less than 100 in order to print all the values of x during "while" loop executes the System.out.println("x = " + x); is used.
Here java will send each value of x to output console by appending it to the "x = " string(text) so on each iteration of while loop you will get output on console like
x = 1
x = 2
x = 3
and so on...
x = 99
The + operator concatenates if the operands' type is string, and it performs summing if the operands are ints, floats or doubles.
Here is the out put:
X = 1, X = 2, X = 3, X = 6, X = 7, X = 14, X = 15, X = 30, X = 31, X = 62, X = 63...
The user should enter the values to x and y, and if x is greater than 5 and and when y= 0 , then z should be equivalent to x+y. However, when I compile it gives me an error saying that z might not have been initialized.
import java.util.Scanner;
public class add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
System.out.print("Enter a value for x");
int x = input.nextInt();
System.out.print("\nEnter a value for y ");
int y = input.nextInt();
int z;
if (x > 5){
if (y == 0)
z = x + y;
System.out.println("The answer is " + z);
}
else
System.out.println("The answer is only" + x);
}
}
There is an execution path where z doesn't get initialized, but you attempt to print it. If x is greater than 5, but y isn't 0, then z is not initialized, but you refer to z when printing it.
Use braces to create an inner block for your inner if statement, so z is only referenced if it's initialized:
if (x > 5){
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Also, proper indenting helps to identify visually what's part of a block and what's not.
Your 'if' statement is misleading:
if (y == 0)
z = x + y;
What if y != 0? In that case, z is not initialized.
The next line
System.out.println("The answer is " + z);
doesn't apply to the y==0 statement, as you don't have braces {}.
You probably meant to write something like:
if (x > 5) {
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Note the "{" after the if statement.
As you are not using braces for if condition, your z will not initialized.
To solve such kind problems always keep in mind that if you are calculating something with integer variable do initialize them with some value (here, 0 is the best).
Then you can access that variable anywhere in the code without any initialization error.
To rid of this problem, you have two ways
One way:
just simply initialize your z variable like:
int z=0;
Second way:
Try to put braces for if condition like:
if (y == 0){
z = x + y;
System.out.println("The answer is " + z);
}
You need to assure the compiler that z will get a value no matter what.
You may want to assign it a default value when declaring it.
Something along these lines:
int z = 0; // just an example
int z has no value, try the code at the bottom then give it a 0 or input.nextInt();
int z = 0;
or
int z = input.nextInt();