How to find whether a number is odd or even, without using if condition or ternary operators in Java?
This question is given by my teacher. He also give me a hint that it is possible by using a bitwise operator.
There are few ways to not use if and get behavior that will be same as if if was used, like ternary operator condition ? valueIfTrue : valueIfFalse or switch/case.
But to be tricky you can also use arrays and try to figure some transformation of our value to proper array index. In this case your code could look like
int number = 13;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);
output:
13 is odd
You can change number % 2 with number & 1 to use suggestion of your teacher. Explanation of how it works can be found here.
Consider a number's representation in binary format (E.g., 5 would be 0b101).
An odd number has a "1" as its singles digit, an even number had a zero there. So all you have to do is bitwise-and it with 1 to extract only that digit, and examine the result:
public static boolean isEven (int num) {
return (num & 1) == 0;
}
int isOdd = (number & 1);
isOdd will be 1 if number is odd, otherwise it will be 0.
Did you mean something like this?
boolean isEven(int value) {
return value % 2 == 0;
}
boolean isOdd(int value) {
return value % 2 == 1;
}
Every odd number have 1 at the end of its binary representation.
Sample :
public static boolean isEven(int num) {
return (num & 1) == 0;
}
Just saw now 'Without using IF'
boolean isEven(double num) { return (num % 2 == 0) }
Just a quick wrapper over the already defined process...
public String OddEven(int n){
String oe[] = new String[]{"even","odd"};
return oe[n & 1];
}
I would use:
( (x%2)==0 ? return "x is even" : return "x is odd");
One line code.
Method 1:
System.out.println(new String[]{"even","odd"}[Math.abs(n%2)]);
Method 2:
System.out.println(new String[]{"odd","even"}[(n|1)-n]);
Method 1 differs from the accepted answer in the way that it accounts for negative numbers as well, which are also considered for even/odd.
import java.util.Scanner;
public class EvenOddExample
{
public static void main(String[] args)
{
System.out.println("\nEnter any Number To check Even or Odd");
Scanner sc=new Scanner(System.in);
int no=sc.nextInt();
int no1=no;
while (no>1)
{
no=no-2;
}
if(no==0)
{
System.out.println(no1 +" is evenNumber");
}
else
{
System.out.println(no1 +" is odd Number");
}
}
}
you can also use bitwise shift operators
(number >> 1)<<1 == number then even else odd
# /* **this program find number is odd or even without using if-else,
## switch-case, neither any java library function...*/
##//find odd and even number without using any condition
class OddEven {
public static void main(String[] args) {
int number = 14;
String[] trick = { "even", "odd" };
System.out.println(number + " is " + trick[number % 2]);
}
}
/**************OUTPUT*************
// 14 is even
// ...................
//13 is odd
Related
College assignment for testing a positive number (called num) is a Prime Number or not.
I must use a Do while loop
Ive attempted the code as follows but its failing the test
public class Primes {
public static main void (String args[]){
int num = 1;
int 2 = 0;
boolean flag = false;
do {
if (num%i == 1) {
flag = true;
break:
}
num ++
while (i<=num);
{
if (flag = true);
{
System.out.println (num + "is a prime number ");
}
else
{
System.out.prinln (num + "is not a prime number ");
}
}
}
}
1. Main function signature
it should be
public static void main(String args[])
not
public static main void (String args[])
2. you cannot start a variable name with a number
int 2 = 0;
you probably mean
int i = 0;
3. do { ... } while(...);
The format of a do while loop is
do {
something();
} while (condition);
4. Semicolon means end of statement
while (condition); {
something();
}
in this case something() is not in your while loop
5. Watch out for assignment in if
if (flag = true)
this is assigning flag to true. And the condition is always true (since the resulting of the assignment is true).
6. Not System.out.prinln
It is System.out.println. Use an IDE.
Final solution
public class Primes {
public static void main(String args[]) {
int num = 3;
int i = 2;
boolean flag = false;
do {
if (num % i == 0) {
flag = true;
break;
}
i++;
} while (i < num);
if (!flag) {
System.out.println(num + " is a prime number ");
} else {
System.out.println(num + " is not a prime number ");
}
}
}
I also fixed some logical problem such as
you should probably increment i instead of num,
while (i < num) instead of while (i<=num), otherwise some (last) i always equals to num, making everything not a prime
a number is not a prime when flag is true. you should probably invert the if logic. Flag is true when you find something that is evenly divisible, meaning the number is not a prime.
There are better solutions, but I stick with your format.
You have a couple of different issues:
Firstly, it should be:
public static void main(String[] args){
Second, your variable on line 4 doesn't have name.
Your format for your do while statement is also, not quite right.
Another poster has a good example of a do while loop here:
Do-while loop java explanation
Also, go over the rules for where semicolons should be placed.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
Objective:
(Palindrome integer) Write the methods with the following headers:
// Return the reversal of an integer, i.e., reverse(456) returns 654
public static int reverse(int number)
// Return true if number is a palindrome
public static boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a palindrome
if its reversal is the same as itself. Write a test program that prompts the
user to enter an integer and reports whether the integer is a palindrome.
My code is below... My attempt is below. I've collapsed and I don't know what else to do BUT come here. I'm stuck on the Boolean portion of the code and do not know if the rest of this code is right. I've scoured the internet and seen very few examples but none of them made any sense. I'm a visual learner, so none of this really makes sense to me. Started Java 2 months ago so please don't expect me to produce gold with extremely limited knowledge. I need help-help, not petty or witty comments. If you don't want to offer help, don't comment.
public class NewClass {
public static int reverse(int number) {
int remainder = 0;
while (number != 0) {
remainder = number % 10;
number = number / 10;
System.out.print(remainder);
}
System.out.println(" is the reverse number.");
return remainder;
}
//I don't really know what to do here.
public static boolean isPalindrome(int number, int remainder) {
return number == remainder;
}
//Nor do I know what I'm doing here. I'm supposed to make the result from 'reverse' either true or false but I don't know what it write, considering the 'Boolean' portion is unfinished.
public static void main(String[] args) {
System.out.print("Enter an integer: ");
java.util.Scanner input = new java.util.Scanner(System.in);
int number = input.nextInt();
reverse(number);
int remainder = 0;
if ( remainder == ture)
}
}
Revised:
public class NewClass {
public static int reverse(int number) {
int reverse = 0;
while (number != 0) {
reverse = (reverse * 10) + number % 10;
number = number / 10;
System.out.print(reverse);
}
System.out.println(" is the reverse number.");
return (reverse);
}
public static boolean isPalindrome(int number) {
return (number == reverse(number)); //Still being asked to introduce this line. I don't know what that means. My book says nothing and the internets isn't helping.
}
public static void main(String[] args) {
System.out.print("Enter an integer: ");
java.util.Scanner input = new java.util.Scanner(System.in);
int number = input.nextInt();
reverse(number);
if (number == reverse(number)) {
System.out.println(number + " is a palindrome");
}
else{
System.out.println(number + " is not a palindrome");
}
}
}
**Results:
run:
Enter an integer: 121
112121 is the reverse number.
112121 is the reverse number.
121 is a palindrome
BUILD SUCCESSFUL (total time: 2 seconds)**
My question: I don't know what I'm doing with the true and false portion of this code. The point is to check the number, compare it to the reversed number checking whether it is a palindrome or not. The second issue is with the reverse number repeating itself with double the number... I don't know what I'm doing wrong or how to fix it.
Query:
public static boolean isPalindrome(int number) {
return (number == reverse(number));
}
I'm being asked to introduce this line but I don't know what it means. It's the only error I have. It's supposed to return the true or false, correct? What do I do with it because it seems like I created a code that doesn't need that specific line, even though it is required.
If you're talking about how to implement isPalindrome in terms of reverse, it's simply figuring out if the number and its reverse are the same.
So, for example, 767 is a palindrome because, when reversed, it's equal to the original. However, 314159 is not a palindrome because its reversal is a totally different number, 951413.
That means pseudo-code like this should suffice (I've included reverse because your current implementation, while close, returns the final remainder rather than the reversed number):
def reverse(num):
rnum = 0
while num != 0:
rnum = (rnum * 10) + (num % 10)
num = num / 10
return rnum
def isPalindrome(num):
return (num == reverse(num))
If you want to nut it out yourself, don't look below. This is how I'd approach it for this level of skill and I'm providing it just for completeness.
public class Test {
public static int reverse (int num) {
int rnum = 0;
while (num > 0) {
rnum = (rnum * 10) + (num % 10);
num = num / 10;
}
return rnum;
}
public static boolean isPalindrome (int num) {
return (num == reverse (num));
}
public static void main(String args[])
{
System.out.println(isPalindrome (767));
System.out.println(isPalindrome (12321));
System.out.println(isPalindrome (4));
System.out.println(isPalindrome (314159));
}
}
I personally use my two methods for doing it, but the guy who did the StringBuilder thing did good too :).
Here is my code for reversal and then I call that and check if it a palindrome.
public static String reverseString(String str)
{
String blank = "";
for(int i = str.length()-1; i >= 0; i--)
{
blank = blank + str.charAt(i);
}
return blank;
}
// NOW you can call isPalindrome("Whatever string you wanna check.");
public static boolean isPalindrome(String str)
{
String reverse = reverseString(str);
if(str.equalsIgnoreCase(reverse))
{
return true;
}
else
{
return false;
}
}
Here is example for check the given number is palindrome or not .
public static void main(String [] args) {
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome + " is a palindrome");
}else{
System.out.println("Number : " + palindrome + " is not a palindrome");
}
}
/*
* Java method to check if number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
}
How do I change the code....
if (yourAnswer = numberOne + numberTwo)
{
System.out.println("That is correct!");
counter = counter + 1;
}
else
{
System.out.println("That is incorrect!");
}
This does not seem to be working for me. Can anyone help me?. The debugger is saying:
RandomNumbersProgramThree.java:21: error: incompatible types: int cannot be converted to boolean".
You cannot associate a number with a Boolean value. A boolean is true or false, not a number, however you can create a variable that indicates if a certain number represents true or false. Is this your entire program? I would like to see what "yourAnswer", "numberOne", and "numberTwo" are stored. but for now I will write a pseudo-program to explain the theory.
import java.util.*;
public class ExampleProgram
{
public static void main(String[] args)
{
System.out.println("Please enter two numbers");
Scanner answer = new Scanner (System.in);
int yourAnswer = answer.nextInt();
int numberOne = 1;
int numberTwo = 2;
if (yourAnswer == (numberOne + numberTwo))
{
System.out.println("That is correct!");
}
else
{
System.out.println("That is incorrect!");
}
}
}
This program will ask the user to input a number, for example the number "3". It will then compare that number to the two numbers you declares, "numberOne" which equals the value of one, and "numberTwo" which equals the value of two. Therefore, in the "IF" statement it says, "If (yourAnswer == (numberOne + numberTwo))" which means that 1 + 2 = 3, if the users answer is 3, then 3 = 3 and the result will come back as true.
In the if statement, you are using an '=' sign, this type of equal sign is not a comparison '=' but is used to set a value to an variable. ie, int x = 2;
The type of equals you need is the type that is used in comparisons, which is ==. You always use == when dealing with boolean comparisons
I'm an aspiring java user taking college courses and I've run into a problem. My prof. told us to write a java program that detects a 5 digit number based palindrome. I've written something but it won't work the way I've planned. Could I get some help please? Using netbeans IDE.
package palindrome;
import javax.swing.JOptionPane;
public class Palindrome {
public static void main(String[] args) {
String stringNumber;
int number;
String stringPal;
int palindrome;
stringNumber = JOptionPane
.showInputDialog("Please, if you will, enter a five digit palindrome: ");
number = Integer.parseInt(stringNumber);
if (number < 10000 && number > 99999) {
System.out
.println("Your number is invalid, please enter a FIVE digit number: ");
} else if (number % 10 == number % 100) {
System.out.println("your number: " + number + "is a palindrome");
} else {
System.out.println("You FAIL loser");
}
}
}
Your palindrome logic is incorrect. You check if the remainder when divided by 10 equals the remainder when divided by 100 - that is the case if and only if there is a 0 in the tens digit. That is not the definition of a palindrome.
As already pointed out, that your logic for palindrome is wrong.
What you need to check is if the string/number is same when reversed.
So, suppose you want to check whether the a string is palindrome, reverse it and check if it is same as the original string.
You should try to complete this template:
boolean isPalindrome(String s){
String reverseString = reverseString(s);
if(reverseString.equals(s)){
return true;
}
return false;
}
String reverse(String s){
//add code to reverse String. (and optionally check if it is Integer, if it is a requirement)
}
You can now google how to reverse a string.
PS: You might wanna take a look at StringBuilder class.
i don't understand, how number % 10 == number % 100, implies palindrome, but all it does is compare the value of the last 2 digits to the value of the last 1 digit.
My advice would be to take input as a string or char array and the compare the last element of the string to the first, and then continue until you hit the middle
here's some psudo-code:
isPalindrome = true;
for i=0 to stringLength
if(input[i] != input[length - i - 1])
isPalindrome = false;
I have the following code and i want to print the palindrome on console. Please let me know what should come inside the if condition so that it can print all palindrome in between 0 to 10000.
The palindrome is 161, 1221, 4554, etc....
Java code:
int palindrome[];
palindrome = new int[10000];
for (int count = 0; count < palindrome.length; count++ ){
palindrome[count] = 0;
if(){
System.out.println(count);
}
}
This will do:
if (isPalindrome(count)) {
System.out.println(count);
}
...
public boolean isPalindrome(int num) {
// implement method here (ie: do your homework)
}
Something like this might work
public boolean isPalindrome(final int num) {
final String s = Integer.toString(num);
return s.equals(new StringBuffer(s).reverse().toString());
}
You need to transform the number into a string and then check if the string reversed is equal to the original string. This looks a lot like some homework, if so please add the appropriate tag.
The code golf solution:
public static boolean isPalindrome(int number) {
return ("" + number).equals(new StringBuilder("" + number).reverse().toString());
}
You could also reverse the number and check if the reversed one and your number are equal.
To reverse the number: keep dividing it with 10 until the result is 0. Save the remainders of the divisions. Starting from the first remainder you get, multiply it by 10 and add the next remainder. Keep multiplying by 10 and adding remainders till you use all the remainders.
To revers I use a StringBuffer, StringBuffer(num).reverse().toString();
Here are some hints:
a) To get the last digit of a number use the remainder (%) operator
Example:
result = number % 10; // 21 % 10 = 1
b) To cut of the last digit, divide by 10
Example:
number = number / 10; // 21 / 10 = 2;
c) Multiply the result by 10
Example:
result = result * 10; // 1 * 10 = 10
d) Repeat until some condition is fulfilled (shouldn't be too hard to figure out ;-))
boolean isPalin(int n)
{
String s = Integer.toString(n);
return s.equals( new StringBuffer(s).reverse().toString() );
}
so your if condition should contain: isPalin(count)
boolean isPalin(int n)
{
int nn = 0, tmp = n;
while(n > 0)
{
nn = nn*10 + n%10;
n /= 10;
}
return tmp==nn;
}
I prefer doing it this way instead of using strings, since strings make the process slow as it involves a lot of overhead.
import java.util.*;
import java.io.*;
public class TestFinal {
public static Scanner c = new Scanner(System.in);
public static void main(String[] args) {
String original ,reverse ="";
// TODO, add your application code
System.out.println("Enter the text!");
original = c.next();
int length = original.length();
for(int i =length - 1;i >= 0;i--)
reverse = reverse +original.charAt(i);
if(original.equals(reverse))
System.out.println("entered strig is a palindrome");
else
System.out.println("the text is not a palindrome");
}
}
An easy way to print palindrome:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
/* Enter your code here. Print output to STDOUT. */
int len = A.length();
String B ="";
for(int i=len-1;i>=0;i--){
B=B+A.charAt(i);
}
if(A.equals(B))
System.out.println("Yes");
else
System.out.println("No");
}
}