Basically is about the binary numbers, the user needs to input two random numbers, both numbers will be added, and the addition of those two numbers only needs to have ones and zeros for example 5+6==11 OR 55+55=110, then throw a message saying “the addition only has 1’s and 0’s, otherwise for example 25+46=71 or 575+575=1150 then a message saying the addition does not have only 1’s and 0’s.
I just started learning java and i can’t find anything helpful for this problem, i already know the conditionals if only have ones and zeros or not.
this is the code i already have, but when i input for example 575+575+1150 says only has 1's and 0's, i guess i cant use .contains for this.
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int n1;
int n2;
int add;
System.out.print("Input Number 1: ");
n1=read.nextInt();
System.out.print("Input number 2: ");
n2=read.nextInt();
System.out.println();
add=n1+n2;
System.out.println("The addition is = "+add);
String S = String.valueOf(add);
if(S.contains("1") && S.contains("0")) {
System.out.print("The addition only has 1's and 0's");
}
else{System.out.print("The addition does not only have 1's and 0's");}
}
}
I saw your code and and the resultant sum 1150 does contain 1's and 0's.
s.contains(x);
This function only checks if the string contains the value x or not. Since "1150" contains both 1's and 0's therefore your function prints the wrong output.
One way of solving this problem would be to add the two numbers and then check the resultant sum digit by digit. You can make a function that will do that for you.
public void checkOnesAndZeros(int resultantSum) {
while (resultantSum > 0) {
int remainder = resultantSum % 10;
if(remainder != 1 && remainder != 0) {
System.out.println("The addition does not have only 1’s and 0’s.");
return;
}
resultantSum = resultantSum / 10;
}
System.out.println("The addition only has 1’s and 0’s");
}
One way is to create a String using the added numbers and iterating through the characters.
public static boolean isResultBinary(int n1, int n2) {
String sum = n1 + n2 + "";
for (int i = 0; i < sum.length(); i++) {
char c = sum.charAt(i);
if (c != '1' && c != '0') return false;
}
return true;
}
Here's a method I wrote, it checks every character c to see if it is either '0' and '1'. If a character is not either one, the method will return false. Otherwise, it'll loop through the whole string and return true.
To get your desired output, use this method like this in within your main method:
if (isResultBinary(n1, n2)) System.out.println("The addition only has 1's and 0's");
else System.out.print("The addition does not only have 1's and 0's");
Here is another take on the question.
convert the sum to a string and then try and parse it as binary.
if it isn't binary, an exception will be thrown, so return false.
otherwise return true.
int[] sums = { 110, 120, 10111, 250, 203, 2011, 1110111 };
for (int n : sums) {
System.out.printf("%8s - %s%n", n,
"is " + (checkOnesAndZeros(n) ? "" : "not ")
+ "all ones and zeros");
}
prints
110 - is all ones and zeros
120 - is not all ones and zeros
10111 - is all ones and zeros
250 - is not all ones and zeros
203 - is not all ones and zeros
2011 - is not all ones and zeros
1110111 - is all ones and zeros
The method
public static boolean checkOnesAndZeros(int resultantSum) {
try {
Integer.parseInt(Integer.toString(resultantSum), 2);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Related
The following question was asked in my last interview (yesterday), and I'm trying to solve it since then (couldn't solve it in the interview).
Sorry for any grammar mistakes or any logical mistakes, I don't have the question, it was written by memory:
You are given a number in a string format, for example: "14438832066".
You got to sum up the consecutive equal digits in that number. If no
consecutive equal digit was found, just add the digit to the result.
for example: solution(19938832066) => 11831632012
Explanation: first digit is 1.
The second and third digits are both 9 which means they will turn into 18 in the result string.
So on
with the rest of the digits (as you can see, the last 2 digits are both 6 which means they will turn into 12 in the result string).
You are required to do that for the result string as well, if needed, until no equal consecutive digits are found in the number.
Example:: number: 14438832066 solution( "19938832066") ->"11831632012" -> "2831632012"
Explanation: first result is 11831632012, but then you can see that there are still equal consecutive digits : the first and the
second digits are both 1. So process that number as well.
You are given a string and must return a string.
My solution:
I couldn't write the solution, I don't know why. It's a pretty simple question, I thought going recursive at first but didn't want to complex things.
I wrote 2 helper methods:
one that returns a boolean whether the number consists of equal consecutive digits.
one that actually makes the business logic:
turn the string into a char array
create a counter that will count instances of the same digit - (int counter = 1).
loop on the array from the first to the one before the last element :
inside the loop:
//equal digit was found - increment counter and continue to next digit
if char[i] == char[i+1] then counter++
//calculation in case we are done counting the same digit
else if counter > 0 then result.append(counter*digit[i])
// if no consecutive equal digit was found
else result.append(digit[i])
end loop: return result
Problems I had:
I created the counter inside the loop, so each iteration it got rested. took me few minutes to realize.
I had troubles realizing that 'int(digit[i])' doesn't give me the numeric value of the char, it gives the ASCII value. I had to use "Character.getNumericValue" (don't remember the exact name of the method).
Because of these problems, it took me 45 minutes to write the solution which in the end didn't even work.
I'll be glad to get a working solution, and even better - to get any feedback and tips on my solution and what, in your opinion, were my mistakes.
Thank you.
Your pseudo-code seems alright, as far as it goes. What's missing is that you don't repeatedly check the result string to see if another pass is required. I also show how you don't need to remember the API to convert a character to a digit; if you know the digits are decimal, you can interpret them yourself. As an interviewer, I would accept that there is an API that you can't precisely remember or your home-brew solution as equally valid.
String transform(String number) {
while (true) {
String result = collapse(number);
if (result.equals(number)) return result;
number = result;
}
}
private static String collapse(String number) {
StringBuilder result = new StringBuilder();
for (idx = 0; idx < number.length(); ) {
int mark = idx;
int digit = digitAt(number, idx++);
while (idx < number.length() && digitAt(number, idx) == digit) ++idx;
result.append((idx - mark) * digit);
}
return result.toString();
}
private static int digitAt(String num, int index) {
char ch = number.charAt(index);
if (ch < '0' || ch > '9') throw new IllegalArgumentException();
return ch - '0';
}
The preceding is a naïve approach that transforms the string until there are no changes. I suspect there might be a more "elegant" approach that works from left to right through the input in a single pass, but it would take some thought, and I probably couldn't come up with that in an interview.
Here's an algorithm that uses recursion and a for-loop to add consecutive equal digits. I think the code is pretty self-explanatory but please ask if you have any queries.
public static String addConsecutiveDigits(String number) {
char[] arr = number.toCharArray();
StringBuilder result = new StringBuilder();
boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits
for (int i = 0; i < arr.length; i++) {
int digit = arr[i] - '0'; //Subtracting ascii values to get integer values
int newNumber = digit;
if (i != arr.length - 1) {
int nextDigit = arr[i + 1] - '0';
if (digit == nextDigit) { // check if the digits are consecutive digits
newNumber = digit + nextDigit;
i++; // increment i as we have already added the i+1 digit
foundConsecutive = true;
}
}
result.append(newNumber);
}
if (!foundConsecutive) // if no consecutive equal digits were found then return the result;
return result.toString();
else // recurse to check for more consecutive equal digits
return addConsecutiveDigits(result.toString());
}
I'm not a Java guy, so this code might not be ideal but I would do something like this:
public String solve(String input)
{
String result = "";
int i = 0;
while (i < input.length())
{
var first = input.charAt(i);
if (i == input.length() - 1){
result += first;
break;
}
var second = input.charAt(i + 1);
if (first == second){
result += (Character.getNumericValue(first) + Character.getNumericValue(second));
i += 2;
} else {
result += first;
i += 1;
}
}
return result;
}
For the second part, I would just run the function in a loop until the result matches the input.
I wrote a program which, at first, was giving correct answers however I later wrote another method which caused my program to start failing. After that I deleted the second method but nothing seems to work to fix it. Can you guys tell me what the problem is?
Note: Method isNumeric just checks if the input String contains a non-numeric character.
For example: a number in octal basis "115" needs to be converted to decimal, meaning
(115)8 -> (?)10
The following formula gives us this:
115 = (1 × 8²) + (1 × 8¹) + (5 × 8⁰) = 77
This is the formula that the code is supposed to follow.
Therefore the result of the conversion of 115 in octal basis to decimal is 77.
Another limitation of this is that this must use recursion.
It worked in the sense that it gave the correct result 5 times in a row for different String number inputs but something along the way changed and now gives wrong results.
public static int octalStringToDecimal(String numString) {
//Base case the numeric value is just 0 or where String is empty
if ((numString.equals(""))) {
return -9999;
}
//the String does not contain numeric characters
if((!isNumeric(numString))){
return -9999;
}
int rem, sum = 0, i = 0, basis = 8;
int number = Integer.parseInt(numString); //this is n
//while our number is not 0 then we keep on parsing
while (number != 0) {
rem = number % 10;
number = number / 10;
sum = rem * ((int) Math.pow(basis, i)) + octalStringToDecimal(String.valueOf(number));
i++;
}
//when out number is equal to 0 then we return the value
return sum;
}
public static boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Your "recursive" method contains a while loop. Recursive methods do not usually contain loops. A recursive method must contain a condition that terminates the recursion. If that condition is not true, then the method changes the arguments it was called with and then calls itself.
Since the parameter to your recursive method is a string, it seemed logical to me to extract the digits of the number using method substring(int, int).
Since the input number is supposed to be an octal number, apart from checking whether it contains only digits, you also need to check whether it is a valid octal number. In other words each digit in the number must be between 0 (zero) and 7 (seven).
In the below code, I initially take the rightmost digit of the input number and multiply it by 80. Then, in every recursive call, I take the digit immediately to the left of the last digit I converted and increase the exponent by one. Hence, the first recursive call will take the digit to the left of the rightmost digit and multiply it by 81.
Once I have converted the leftmost digit, the recursion stops.
public class Converter {
private static final int BASE = 8;
private static void checkDigit(String digit) {
int numeral = Integer.parseInt(digit);
if (numeral > 7) {
throw new IllegalArgumentException("Not a valid octal digit: " + digit);
}
}
private static int convertDigit(String digit, int exponent) {
return (int) Math.pow(BASE, exponent) * Integer.parseInt(digit);
}
private static int octalStringToDecimal(String numString, int exponent, int start) {
if (start >= 0) {
String digit = numString.substring(start, start + 1);
checkDigit(digit);
return convertDigit(digit, exponent) + octalStringToDecimal(numString, exponent + 1, start - 1);
}
else {
return 0;
}
}
public static void main(String[] args) {
String numString = "115";
System.out.println(octalStringToDecimal(numString, 0, numString.length() - 1));
}
}
How can I find multiples of a given bit sequence?
So the code should work like this:
int bit = 0b100
for (int i = 0; i<=50;i++){
if (bit in i){
print(i);
}
}
This should print 4 (100) and 36 (100100).
I was trying to iterate through it and bit-mask it but it also printed numbers like 40 (101000).
So it should only print numbers containing only multiplies of that sequence (100, 100100, 100100100 ...) but not numbers like 1100, 1001001 ...
You can use the modulo operator and shift operator to check the lower bits of the number and "reduce" the incoming number to check the next lower bits of the remaining number. The algorithm works like this:
Do a modulo of the sequence on the number to check. The modulo must be 0.
So when you have the sequence 0b100 and you have a number to check like 0bXXXXXXXX101 the modulo would be 0b001, which is not 0 and you know the number can't be a sequence of multiple 0b100s.
Shift the remaining number to the right, since you have already checked the first N bits on the right.
You shift the number with the >> operator. This will move the bits to the right, dropping the already checked bits:
0bXXXXXXXX101
0bXXXXXXXX (shifted to the right)
The tricky part is to calculate how big the shift is. You can use log2() to figure that out. When you completed the shift, you go back to point 1 above.
The complete code can look like this:
public static boolean isMultipleOfSequence(int sequence, int number) {
if (sequence == 0) {
return number == 0;
}
while (number != 0) {
int remaining = number % sequence;
if (remaining != 0) {
return false;
}
int shift = log2(sequence);
number = number >> shift;
}
return true;
}
public static int log2(int value) {
return Integer.SIZE-Integer.numberOfLeadingZeros(value);
}
When you try it with the following code:
System.out.println(isMultipleOfSequence(0b100, 0b100));
System.out.println(isMultipleOfSequence(0b100, 0b100100));
System.out.println(isMultipleOfSequence(0b100, 0b100100100));
System.out.println(isMultipleOfSequence(0b100, 0b101100100));
System.out.println(isMultipleOfSequence(0b100, 0b100110100));
System.out.println(isMultipleOfSequence(0b101, 0b101101101));
System.out.println(isMultipleOfSequence(0b101, 0b100101101));
You will get the following output:
true
true
true
false
false
true
false
You might need to check for negative inputs as this method only works for positive numbers.
I'm not sure how to do it with pure math, but regex works:
Pattern pattern = Pattern.compile("^(100)+$");
for (int i = 0; i < 100; i++) {
String binary = Integer.toBinaryString(i);
if (pattern.matcher(binary).find()) {
System.out.println(i + " " + binary);
}
}
Edit: What about going the other direction?
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++) {
builder.append("100");
System.out.println(Integer.parseInt(builder.toString(), 2));
}
This question was asked in an interview (about prime numbers)
Russian Doll Primes
They are more commonly known as Truncatable Primes.
I found this code on wiki
public static void main(String[] args){
final int MAX = 1000000;
//Sieve of Eratosthenes (using BitSet only for odd numbers)
BitSet primeList = new BitSet(MAX>>1);
primeList.set(0,primeList.size(),true);
int sqroot = (int) Math.sqrt(MAX);
primeList.clear(0);
for(int num = 3; num <= sqroot; num+=2)
{
if( primeList.get(num >> 1) )
{
int inc = num << 1;
for(int factor = num * num; factor < MAX; factor += inc)
{
//if( ((factor) & 1) == 1)
//{
primeList.clear(factor >> 1);
//}
}
}
}
//Find Largest Truncatable Prime. (so we start from 1000000 - 1
int rightTrunc = -1, leftTrunc = -1;
for(int prime = (MAX - 1) | 1; prime >= 3; prime -= 2)
{
if(primeList.get(prime>>1))
{
//Already found Right Truncatable Prime?
if(rightTrunc == -1)
{
int right = prime;
while(right > 0 && primeList.get(right >> 1)) right /= 10;
if(right == 0) rightTrunc = prime;
}
//Already found Left Truncatable Prime?
if(leftTrunc == -1 )
{
//Left Truncation
String left = Integer.toString(prime);
if(!left.contains("0"))
{
while( left.length() > 0 ){
int iLeft = Integer.parseInt(left);
if(!primeList.get( iLeft >> 1)) break;
left = left.substring(1);
}
if(left.length() == 0) leftTrunc = prime;
}
}
if(leftTrunc != -1 && rightTrunc != -1) //Found both? then Stop loop
{
break;
}
}
}
System.out.println("Left Truncatable : " + leftTrunc);
System.out.println("Right Truncatable : " + rightTrunc);
}
This gives the output:
Left Truncatable : 998443
Right Truncatable : 796339
But I am not able to solve this particular Russian doll prime number problem like if you have a prime number and you remove either left or right digit of this prime number then if that resulting number is prime number or not?
I am new to this so please pardon any mistake.
Let's start from the beginning:
According to the link you supplied with your question:
"Russian Doll Primes are
prime numbers whose right digit can be repeatedly removed, and are
still prime."
I will assume that you have a function boolean isPrime(int) to find out if a number is prime.
Googling, we will find from Wikipedia that the number of right-truncatable prime numbers up to 73,939,133 is 83, which makes brute-force a viable option; but a few optimization techniques can be employed here:
Since we right-truncate, we can safely eliminate even numbers (since any even number won't be prime, and so any number generated upon it will never be a russian doll prime).
Since any number that starts with 5 is divisible by 5, then based on the same rule I mentioned in the previous point, we can eliminate 5.
That leaves us with numbers that contain 1, 3, 7, and 9.
Now if we wanted to generate all possible combinations of these 4 numbers that do not exceed the maximum you mentioned (1,000,000), it would take only 4,096 iterations.
The downside of this technique is that we now have 4,096 numbers that contain possible non-prime numbers, or prime numbers that are formed from non-prime numbers and hence are not russian doll primes. We can eliminate these numbers by looping through them and checking; or better yet, we can examine russian doll primes more closely.
Upon examining the rule I quoted from your link above, we find that a russian doll primes are prime numbers whose right digit can be repeatedly removed, and are still prime (and hence are still russian doll prime, given the word repeatedly)!
That means we can work from the smallest single-digit russian doll primes, work our generation magic that we used above, and since any prime number that is formed from russian doll prime numbers is a russian doll prime number, we can eliminate non-primes early on, resulting in a clean list of russian doll prime numbers, while reducing the running time of such a program dramatically.
Take a look at the generation code below:
void russianDollPrimesGeneration(int x) {
x *= 10;
if (x * 10 >= 1000000) return;
int j;
for (int i=1; i<=9; i+=2) {
if (i == 5) continue;
j = x + i;
if (isPrime(j)) {
addToRussianDollPrimesList(j);
russianDollPrimesGeneration(j);
}
}
}
Provided that void addToRussianDollPrimesList(int x) is a function that adds x to a list that we previously preserved to store the russian doll prime numbers.
UPDATED NOTE
Note that you can put the call to void russianDollPrimesGeneration(int x) that we made inside the if condition inside the void addToRussianDollPrimesList(int x) function, because whenever we call the former function, we will always call the latter function with the same arguments. I'm separating them here to emphasize the recursive nature of the generation function.
Also note that you must run this function with the integer 0.
A final note is that there are a number of cases that the generation function void russianDollPrimesGeneration(int x) above won't count, even though they are Russian Doll Primes.
Remember when we omitted 2 and 5, because even numbers and numbers divided by 5 cannot be primes and so cannot be Russian Doll Primes? and consequently cannot form Russian Doll Primes? Well, that case does not apply to 2 and 5, because they are prime, and since they are single digits, therefore they are Russian Doll Primes, and are eligible to form Russian Doll Primes, if placed in the left-side, like 23 and 53.
So how to correct our code to include these special cases?
We can make a wrapper function that adds these two numbers and checks for Russian Doll Primes that can be formed using them (which will be the same generation function we are using above).
void generationWrapperFunction(int x) {
addToRussianDollPrimesList(2);
russianDollPrimesGeneration(2);
addToRussianDollPrimesList(5);
russianDollPrimesGeneration(5);
russianDollPrimesGeneration(0);
}
END UPDATED NOTE
This little function will produce a list of russian doll prime numbers, which can then be searched for the number we are looking for.
An alternative, yet I believe will be more time-consuming, is the following recursive function:
boolean isRussianDollPrime(int n) {
if (!isPrime(n)) return false;
if (n < 10) return true;
return isRussianDollPrime(n / 10);
}
This function can be modified to work with left-truncatable primes. The generation-based solution, however, will be much difficult to implement for left-truncatable primes.
Your problem is to use this code or to solve the problem ?
if to solve it you can generate primes using Sieve algorithm then check if the element is prime or not (if it was prime then check if element/10 is also prime)
Let's start with a simple assumption that we know how to write code to detect if a value is a prime. In a coding interview, they won't likely won't expect you to pull out "Sieve of Eratosthenes". You should start with simple code that handles the special cases of x<=1 (false) and x==2(true). Then check for an even number !(x % 2)(false). Then loop on i from 3..sqrt(x) (incrementing by +2 each time) to see if there's an odd number divisor for x.
boolean isPrime(long x)
{
// your code goes here
}
And once we have a function to tell us if a value is prime, we can easily build the function to detect if a value is a Russian Prime. Therefore we just need to loop on our value, each time check for prime, and then chop off the right hand side. And the easiest way to remove the right-most digit from a number is to simply divide it by 10.
boolean isRussianPrime(long x)
{
boolean result = isPrime(x);
while ((x != 0) && result)
{
// chop off the right digit of x
x = x / 10;
if (x != 0)
{
result = isPrime(x);
}
}
return result;
}
And that's really all there is to it.
package com.example.tests;
public class RussianDollPrimeNumber {
public static void main(String[] args) {
int x= 373;
int k;
int n =x;
for ( k= String.valueOf(x).length()-1;k>0;k--){
System.out.println(n);
if (isPrime(n)){
String m=String.valueOf(n).substring(0, k);
n=Integer.parseInt(m);
continue;
}else {
break;
}
}
if( k==0){
System.out.println("Number is Russianl Doll Number "+x);
}else {
System.out.println("Number is not Russianl Doll Number "+x);
}
}
private static boolean isPrime(int x) {
boolean check=true;
for (int i=2;i<x/2;i++){
if( (x%i)==0){
check=false;
}
}
return check;
}
}
I have to write a code for printing all palindrome numbers up to 1000. Here is my code. I have dealt with 3 scenarios:
1-digit number
2-digit number
3-digit number
My third scenario is not printing just the palindromes but prints all the numbers. A hint will help me solve this.
public class PrintPalindrome {
public static void main(String args[])
{
Integer[] array=new Integer[1000];
for(int i=0;i<array.length;i++)
{
array[i]=i+1;
printPalindrome(array[i]);
//System.out.println(array[i]);
}
}
public static void printPalindrome(Integer a)
{
String num=Integer.toString(a);
int length=num.length()-1;
//System.out.println(num);
if(num.length()<=1)
{
System.out.println("" + num);
}
else if(num.length()==2)
{
if(num.charAt(0)==num.charAt(1))
System.out.println(num);
}
else if(num.length()>2)
{
//now deal with the numbers whose length is greater than 2
for(int i=0;i<=length;i++)
{
if(num.charAt(i)==num.charAt(length-i))
System.out.println(num);
}
}
}
}
Work out a solution with arithmetic…
This doesn't necessarily help with the code that you've already got, but it's approach to the problem in the title, How to print all palindromes upto 1000, which may be helpful to others who come across this question. It's often fun to try to solve these problems using the properties of the numbers, without worrying about converting them to strings. In this case, note that for any number n, you can get the leading digit by n % 10, that is, the remainder of n divided by 10, or n modulo 10. You can get the number whose digits are the same as the remaining digits of n as the integer quotient of n/10. E.g.,
1234 % 10 = 4
1234 / 10 = 123
Now, if you keep applying this deconstruction, you can get the individuals digits:
123 % 10 = 3
123 / 10 = 12
12 % 10 = 2
12 / 10 = 1
1 % 10 = 1
1 / 10 = 0
Now, if you take those numbers in the same order that you got them (4, 3, 2, 1), you can reconstruct the "reverse" number:
1 + 10(2 + 10(3 + 10(4 + 0))) = 4321
If we call this the reverse of a number, then number is a palindrome if and only if it's equal to it's reverse.
…and then translate it to Java
This is fairly straightforward to implement in Java, and it doesn't require any special casing about 1-digit numbers, 2-digit numbers, etc., or string manipulation. (As Kent points out in the comments, there's still a limit on how large the numbers that this handles is, but if you need to handle big numbers, you could (i) switch to a long; (ii) switch to a BigInteger.)
public class PalindromeExample {
/**
* Returns the number whose digits (base 10) are the reverse
* of number's (with no leading zeros).
* #param number the number to reverse
* #return the reversed number
*/
public static int reverse( int number ) {
int result = 0;
while ( number > 0 ) {
result = result * 10 + (number % 10);
number = number / 10;
}
return result;
}
/**
* Show the numbers less than 10000 whose digit sequences
* are palindromes.
*/
public static void main(String[] args) {
for ( int i = 0; i < 10000; i++ ) {
if ( i == reverse( i ) ) {
System.out.println( i );
}
}
}
}
0
1
2
3
…
9
11
22
…
99
101
111
…
151
161
…
8008
8118
…
9339
9449
9559
9669
9779
9889
9999
if(num.charAt(i)==num.charAt(length)-i)
is wrong. Even if you set parenthesis in the "right" place you still be wrong, because for example:
charAt(0) == charAt(3) //and what's char at 3?
if(num.charAt(i)==num.charAt(length-i-1))
should do the trick but then placing it in a for loop doesnt make any sense.
When a 3-digit number has 1st and 3rd digit the same it is actually a palindrome. Every other loop will just mess up your output.
For the requirement, we don't have to convert to string.
pls try if this works for you: (could be an one-liner)
for (int i = 1; i < 1000; i++)
if (i<10 ||(i<100&&i%11==0)||(i>100&&i%10==i/100) )
System.out.println(i);
Handling scenarios for each digit length to check if a number is a palindrome is not an appropriate approach.
Trying what the other answers suggest - like going through each and every number and checking if it is palindrome by reversing number digit by digit is better but even then it is not very efficient as it is brute force.
So, I would like to some suggestions if I may:-
Rather than going for brute force, any other approach if possible is preferable.
Even while resorting to brute force, using the library functions is
better and at least as efficient as any code we can write. ex - Integer.reverse() function for reversing an integer.
I have had a try at generating the palindromes(rather than trying one by one). This is not bug-proof yet as I have not tested extensively but should be able to convey the concept.
public class PrintPalin {
public static void main(String[] args) {
// TODO Auto-generated method stub
//The first palindrome = 1
int i = 1;
while(i<=10000){
System.out.println(i);
i = nextPalin(i);
}
}
static int nextPalin(int i){
StringBuilder sb = new StringBuilder(String.valueOf(i));
int len = sb.length(), right = len/2, left;
if(len%2!=0 || len == 1){
left = right;
}else{
left = right-1;
}
//System.out.println(left + " " + right);
while(right<len && sb.charAt(right)=='9'){
sb.setCharAt(right, '0');
right++;
sb.setCharAt(left, '0');
left--;
}
if(right==len){
sb.insert(0, '1');
//sb.append("1");
sb.setCharAt(right, '1');
}else{
sb.setCharAt(right, (char)(sb.charAt(right)+1));
if(right != left){
sb.setCharAt(left, (char)(sb.charAt(left)+1));
}
}
i = Integer.valueOf(new String(sb));
return i;
}
}
Where the above approach wins is when the density of palindromes per number tried is less when we go for higher numbers but for the range that is asked(0 to 1000) it would not be able to make much difference.
I am open to other approaches. I was thinking may be decoding the addition required to generate the next palindrome number should be faster and better approach instead of using strings the basic idea of both approaches are similar so should not be much difficult(though I am not sure).
I believe you want to check whether the number is a palindrome or not before you print it. You just need to seprate checking and printing like this:
if(num.length()>2)
{
boolean isPalindrome=true;
for(int i=0;i<=length/2;i++) //you compare one half, to the other
{
if(num.charAt(i)!=num.charAt(length-i))
isPalindrome=false;
}
if(isPalindrome)
System.out.println(num);
}
This should work for a number of any length.