Find the value of the sgn function:
Input. One integer x (-109
≤
x ≤ 109
).
Output. Print the value of the sgn
function for the given value of x.
Sample input 1 |
Sample output 1 |
4 |
1 |
|
|
Sample input 2 |
Sample output 2 |
0 |
0 |
|
|
Sample input 3 |
Sample output 3 |
-2 |
-1 |
conditional
statement
Use the
conditional statement to solve the problem.
Let’s consider another solution. Write the condition as
follows:
y = 1 * (x
> 0) + 0 * (x == 0) + (-1) * (x < 0);
or
y = (x >
0) - (x < 0);
For example, if
·
x is positive, then y = 1 – 0 = 1;
·
x = 0, then y = 0 – 0 = 0;
·
x is negative, then y = 0 – 1 = -1;
Algorithm
realization
Read the input value of x.
scanf("%d", &x);
Compute the value of the sgn
function.
if (x > 0) y = 1; else
if (x == 0) y = 0; else
y = -1;
Print the answer.
printf("%d\n", y);
Algorithm
realization – without if
Read the input value of x.
scanf("%d", &x);
Compute the value of the sgn
function.
y = (x > 0) - (x < 0);
Print the answer.
printf("%d\n", y);
Java realization
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int y, x = con.nextInt();
if (x > 0) y = 1; else
if (x == 0) y = 0; else
y = -1;
System.out.println(y);
con.close();
}
}
Python realization
Read the input value of x.
x = int(input())
Compute the value of the sgn
function.
if x > 0: y = 1
elif x == 0: y = 0
else: y = -1
Print the answer.
print(y)
Python realization – without if
Read the
input value of x.
x = int(input())
Compute the value of the sgn function.
y = (x > 0) - (x < 0)
Print the answer.
print(y)