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");
}
}
Related
I am working on some additional exercises for my introduction to programming class, and I cannot figure out what I did wrong regarding the following question:
(Friendly Numbers) An integer is said to be friendly if the leftmost
digit is divisible by 1, the leftmost two digits are divisible by 2,
and the leftmost three digits are divisible by 3, and so on. The
n-digit itself is divisible by n. For example, the number 42325 is
friendly because 4 is divisible by 1, 42 is divisible by 2, 423 is
divisible by 3, 4232 is divisible by 4, and 42325 is divisible by 5.
Write a general method (with or without recursion) with the name
isFriendly that determines whether or not the number is “friendly”
. Write a main method that tests the method isFriendly.
My program is as follows:
import java.util.Scanner;
public class Question4 {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = in.nextLine();
}
public static String isFriendly(String input){
int n = input.length();
int number = Integer.parseInt(input);
String output = "";
for (int i = 0; i<=n; i++){
if (((n/10*i)%i) != 0 ){
output = "Friendly";
}else{
output = "Not friendly";
}
return output;
}
}
}
The error given is: "The result must return a result of type String".
What can I do to solve this problem, and can I write this program in a more efficient way?
Thank you so much for considering this question!
try this:
public static String isFriendly(String input) {
if (input == null || input.length() == 0) return "Not friendly";
int n = input.length();
int number = Integer.parseInt(input);
for (int i = 0; i<=n; i++) {
if (((n/10*i)%i) == 0 ) {
return "Not friendly";
}
}
return "Friendly";
}
Please try my code here I use StringBuilder class to get each actual int then convert it to string then convert it to int everytime the loop iterate
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = in.nextLine();
System.out.println(isFriendly(input));
}
public static String isFriendly(String input)
{
int n = input.length();
String output = "";
StringBuilder sb = new StringBuilder("");
int myIntOutput=0;
for (int i = 0; i<n; ++i)
{
sb.append(input.charAt(i));
if (Integer.parseInt(sb.toString())%(i+1)==0)
{
myIntOutput++;
}
}
if(myIntOutput==n)
{
output="Friendly";
return output;
}
else
{
output="Not Friendly";
return output;
}
}
if this help you consider accepting it as an answer
I have the following code written with the purpose of the program is for the user to input a number i.e. 123 and the program will output it as 1 2 3 vertically. No matter what I do, my program does it as 3 2 1. I need to use a loop in this program and I can't seem to figure it out.
import java.util.Scanner;
public class DigitsDisplay {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int a = getInt("Give a non-negative integer: ");
double backwards = 0;
int reverse;
int numOfDigits = numOfDigits(a);
double place = Math.pow(10, numOfDigits);
while (a != 0) {
reverse = a % 10;
backwards = backwards + place * reverse;
System.out.println(reverse);
a = a / 10;
}
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
public static int numOfDigits(int a) {
int numOfD = (int)(Math.log10(a)) + 1;
return numOfD;
}
}
Reverse the reversed value
Your program is designed to reverse the digits. And it does. If you want to reverse them back, I suggest you append them to a StringBuilder and then reverse that. Like,
StringBuilder sb = new StringBuilder();
while (a != 0) {
reverse = a % 10;
sb.append(reverse).append(System.lineSeparator());
backwards = backwards + place * reverse;
a = a / 10;
}
System.out.print(sb.reverse());
Using a Regular Expression
Your algorithm could be simplified by using String.replaceAll(String, String) with a regular expression that matches and groups all digits of a and then replaces each digit with itself plus a new line. Something like,
int a = getInt("Give a non-negative integer: ");
System.out.println(String.valueOf(a).replaceAll("(\\d)",
"$1" + System.lineSeparator()));
So this is my first programming course and I have an assignment to convert a binary number entered by the user to a decimal. And my binary number should be stored in a a string.
And to check that all my digits are 1s and 0s I need to use a method to make sure it's valid and return true if the the number is correct and false otherwise.
So I did a search and saw that everyone was using the integer.parseInt(String , int radix) method to convert a binary string to int which worked completely fine, however, the only problem is we didn't take this with my professor so I'm not sure if it's OK and that maybe he wants another way to convert it?
So my question is: how can I write this code in another way that doesn't use this method?.
Here's my code:
import java.util.*;
import java.lang.*;
public class Assignment2
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int converttodecimal;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
converttodecimal = Integer.parseInt(st,2);// integer.parseInt(String , int radix);
System.out.println("the equivalent decimal value is: " +converttodecimal );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
}//end of class
This is the output:
enter a binary number to convert to decimal:
110101
the equivalent decimal value is: 53
Thank you in advance I already asked this question else where but I didn't get the answer I wanted.
UPDATE:
I wrote the program again based on your suggestions #akhil_mittal #fabian but if i want to write the converting method in the program itself (not calling the method) how can i do that ?
here's the code:
import java.util.*;
import java.lang.*;
public class Assignment2test
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int result;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
result = convertBinaryToDecimal(st);
System.out.println("the equivalent decimal value is: " + result );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
public static int convertBinaryToDecimal(String st){
double decimal =0;
for(int i=0;i<st.length();i++){
if(st.charAt(i)== '1'){
decimal = decimal + Math.pow(2,st.length()-1-i);
}
}
return (int) decimal;
}
}
//end of class
Do it manually, you can just multiply each digit for the corresponding power of two and sum the results.
Regarding the last part of your question, you can simply use java.lang.Math.pow(2,exponent), there is no specific operator for that if that was what you were wondering.
You can use the bit-shift operator to get powers of 2:
int pow2(int exponent) {
return 1 << exponent;
}
which should be more efficient than Math.pow.
But you could also calculate a binary number like this (example for 0b110101):
((((((1)*2+1)*2+0)*2+1)*2+0)*2+1)
i.e. by repeatedly multiplying by 2 and adding the next digit.
I have written two methods which use basic computation to convert binary to decimal, one takes long and other takes String. You can also use them to check the differences in implementation. The method is very simple and easy to understand.
public static int convertBinaryToDecimal(String binary){
double decimal =0;
for(int i=0;i<binary.length();i++){
if(binary.charAt(i)== '1'){
decimal = decimal + Math.pow(2,binary.length()-1-i);
}
}
return (int) decimal;
}
public static int convertBinaryToDecimal(long numberInBinary){
int decimal = 0;
int power = 0;
while(true){
if(numberInBinary == 0){
break;
} else {
long temp = numberInBinary%10;
decimal += temp*Math.pow(2, power);
numberInBinary = numberInBinary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
int binaryNumber = 110011;
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumber));
String binaryNumberInString = "110011";
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumberInString));
}
If you want to ensure that String only contains 0 and 1 then you can try yourself and let me know if you need any help.
Binary to decimal Conversion without using Integer.parseInt method
public class BinaryDecimal
{
public static int binaryToDecimal(int binary) {
int decimal = 0;
for (int power = 1; binary > 0; power *= 2, binary /= 10)
decimal += power * (binary % 10);
return decimal;
}
public static void main(String a[]) {
System.out.println("11 ===> " + binaryToDecimal(11));
//System.out.println("11 ===> " + binaryToDecimal(Integer.parseInt(a[0]))); //Input from command line
}
}
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;
}
}
I want to check whether a length of an input text is divisible by 2.
so it will be like
if my text length is 3, the result will be 1.5 and it will display not divisible by 2 and
if my text length is 6, the result will be 3.0 and it will display divisible by 2
but my codes will display the output "not divisible by 2" regardless what is the text length.
what have I done wrong?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
result = (double)l/2.0;
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}
}
}
The mod operation is your friend but only with integers...
if (integer % divisibleBy == 0) { do stuff; }
Edit: I also found this page that does a really good job outlining the various uses mod the mod operator and explains why your double mod doesn't work like you expect.
Edit: Also more review of your code; it looks like you divide by 2 and then do mod by 2. So 6/2 = 3 and 3 is not even. Wonder if your code would work if you used 8 -> 8/2 = 4 and 4%2 = 0.
Check the length of the text, then do a modulo to it.
Modulo , an operation which checks if a number will have a remainder if its divided by another number
yourNumber%5 == 0
where yourNumber is the lenght of your String. Take it from here.
First, length() returns an int, and it's simpler to work with integers, so why are you casting the length to double? The % (modulo) operator is meant to work with integers, not doubles; remember, double numbers are floating-point numbers, so there's always room for numerical error if you use them.
Second, you don't need to use so many variables; keep it simple:
a = scan.nextLine();
if(a.length() % 2 == 0)
System.out.println("Length of string is divisible by 2");
else
System.out.println("Length of string is not divisible by 2");
Easier to read (and write), don't you think?
import java.util.Scanner;
public class Test1 {
public static void main (String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
String str = scan.nextLine();
int length = str.length();
if(length % 2 !=0) {
System.out.println("not divisible by 2");
}
else {
System.out.println("divisible by 2");
}
}
}
There were a lot of problems with your code:
You are using a double to store the result for some reason, when it should've been an int
Your variable names are not descriptive of what they are for.
There is no need to initialize variables to a default value only to overwrite them with new values.
haha i hate these little mistakes. i do them all the time. Just switch both to %
String a =null;
int l = 0;
double result = 0.0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your string\n");
a = scan.nextLine();
l = a.length();
//this is your problem
result = (double)l%2.0;
//this is your problem
System.out.println(result);
if((double)result % 2 != .0) {
System.out.println("not divisiable by 2");
}
else {
System.out.println("divisiable by 2");
}