0

I know that you have to use a for loop, and I've narrowed it down to using the length of an integer to compare certain placements of said integer to determine if it's palindromic or not. How would you get the length of the integer though? I don't need a full code, I just need to know how you would get the length since I'm positive that what I'm thinking would work.

EDIT) I got it to work, but I have to separate 10 Palindrome numbers by each line. How does one do that? Should I share my code, if that helps? Like this: 1,2,3,4,5,6,7,8,9,10 11,12,13,14,15,16,17,18,19,20

EDIT #2) I finished this, but I'm not sure whether I should close the question or delete it, since this seems to be a frequent question for others. Thanks, everybody! But, it works. I just reversed the number every loop, and if it equaled the originL, then it was palindromic.

Alier
  • 1
  • 2
  • 1
    I personally would loop until you have found all 100. And to find if the number is palindromic, i would convert it into a String and compare the starting character to the ending character and working my way in to the middle to see if they all are equal. – Therabidpanther Dec 17 '20 at 18:29
  • _Should I share my code_ That depends. Do you want help with your code? Or do you just want someone to post the code that performs your required task? – Abra Dec 18 '20 at 15:04
  • Break the problem into steps. Create an int array to hold 100 elements. Write code to find the first 100 palindromic integers. Write the first 10 elements of the array. Write the second 10 elements of the array. Continue until you've written all 100 elements. – Gilbert Le Blanc Dec 18 '20 at 15:13

5 Answers5

0

Some of the users have already provided pretty good solutions, but to make my answer helpful, I want to complete it, though. So, I will use the same approach : iterating first half of the palindrome, and than adding adding it reversed from the left. But now I'll be iterating through all digit numbers alternating between odd and even number of digits, so we'll get all palindromes needed. Here is my code :

//Number of palindromes
int N = 100;
//Max number of symbols in the first half of palindrome divided by 2
int n = (int) Math.log10(N)/2;
//We'll print first 9 palindromes, that are out of algorithm
System.out.print("11, 22, 33, 44, 55, 66, 77, 88, 99, ");
N -= 9;
int min = 10, max = 100;
//Iterating through all number of digits.
//We'll keep track of number of palindromes using variable N,
//decreasing it every time we print new one.
for(int i = 1; i <= n; i++){
  for(int j = min; j < max && N > 0; j++, N--){
    String firstHalf = String.valueOf(j);
    //Removing one symbol from second half to make digit number odd
    String secondHalf = new StringBuilder(firstHalf).reverse().substring(1).toString();
    System.out.print(firstHalf + secondHalf + ", ");
    if(N%10 == 1) System.out.print("\n");
  }
  if(N <= 0) break;
  for(int j = min; j < max && N > 0; j++, N--){
    String firstHalf = String.valueOf(j);
    String secondHalf = new StringBuilder(firstHalf).reverse().toString();
    System.out.print(firstHalf + secondHalf + ", ");
    if(N%10 == 1) System.out.print("\n");
  }
  min = max;
  max *= 10;
}
romamiyk
  • 11
  • 1
  • 2
  • Sorry! I must not have been clear. I edited the question if that helps. Thanks though, I really appreciate you taking time out of your busy schedule to help dumb me. – Alier Dec 17 '20 at 22:09
  • 1
    Your code will indeed produce palindromes, but the problem statement specifically asks for the "`FIRST` 100 palindromic numbers". How would your code produce `101` for instance? – Idle_Mind Dec 18 '20 at 15:29
0

Since we're posting code, I'll post mine. I don't think the op will just copy my code, but I hope he'll learn and copy my techniques.

Here are my test results.

  11      22      33      44      55      66      77      88      99     101
 111     121     131     141     151     161     171     181     191     202
 212     222     232     242     252     262     272     282     292     303
 313     323     333     343     353     363     373     383     393     404
 414     424     434     444     454     464     474     484     494     505
 515     525     535     545     555     565     575     585     595     606
 616     626     636     646     656     666     676     686     696     707
 717     727     737     747     757     767     777     787     797     808
 818     828     838     848     858     868     878     888     898     909
 919     929     939     949     959     969     979     989     999   1,001

I did exactly what I stated in my comment.

I created an int array of 100 elements.

I generated the first 100 palindromic integers.

I printed the 100 palindromic integers.

By breaking up the process into steps (methods), I was able to focus on one method at a time. I didn't write all the code before I ran the first test. I probably ran 10 tests or so before the code was complete.

Here's the complete runnable code.

import java.text.NumberFormat;

public class PalindromicIntegers {

    public static void main(String[] args) {
        new PalindromicIntegers().generatePalindromicIntegers();
    }
    
    public void generatePalindromicIntegers() {
        printResults(generatePalindromes());
    }

    private int[] generatePalindromes() {
        int[] palindromes = new int[100];
        int value = 11;
        int index = 0;
        
        while (index < 100) {
            if (isPalindrome(value)) {
                palindromes[index++] = value;
            }
            value++;
        }
        
        return palindromes;
    }

    private void printResults(int[] palindromes) {
        NumberFormat numberFormat = NumberFormat.getIntegerInstance();
        String s = numberFormat.format(palindromes[palindromes.length - 1]);
        int length = s.length() + 3;
        String format = "%" + length + "s";
        
        for (int i = 0; i < palindromes.length; i++) {
            s = numberFormat.format(palindromes[i]);
            System.out.print(String.format(format, s));
            if ((i + 1) % 10 == 0) {
                System.out.println();
            }
        }
    }
    
    private boolean isPalindrome(int value) {
        StringBuilder builder = new StringBuilder();
        String s = Integer.toString(value);
        builder.append(s);
        builder.reverse();
        return builder.toString().equals(s);
    }

}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • Your `printResults` method is way too complex and doesn't match what the OP wants at all. They want simply `11,22,33,44,55,66,77,88,99,101` on the first line, and that would be an issue if they used `NumberFormat` because `1,001` could be interpreted as two separate numbers. – Olivier Grégoire Dec 18 '20 at 16:20
  • You could have just used `System.out.prinf(format, s);` – WJS Dec 19 '20 at 15:31
0

I have to separate 10 Palindrome numbers by each line. How does one do that?

Pick your favorite Palindrome Check, then use a simple loop. You can use the % Remainder Operator to determine when you've reached every 10th palindrome:

class Main {
  
  public static void main(String[] args) {
    int counter = 11; // start with the first length of 2 palindrome?
    int palindromesFound = 0;
    while (palindromesFound<100) {
      if (isPalindrome(Integer.toString(counter))) {
        System.out.print(counter);
        palindromesFound++;
        if (palindromesFound%10!=0) {
          System.out.print(",");
        }
        else {
          System.out.println("");
        }
      }
      counter++;
    }
  }

  // Andrew Mao: https://stackoverflow.com/a/15018381/2330053
  public static boolean isPalindrome(String str) {    
    int n = str.length();
    for( int i = 0; i < n/2; i++ )
        if (str.charAt(i) != str.charAt(n-i-1)) return false;
    return true;    
  }

}

Output:

11,22,33,44,55,66,77,88,99,101
111,121,131,141,151,161,171,181,191,202
212,222,232,242,252,262,272,282,292,303
313,323,333,343,353,363,373,383,393,404
414,424,434,444,454,464,474,484,494,505
515,525,535,545,555,565,575,585,595,606
616,626,636,646,656,666,676,686,696,707
717,727,737,747,757,767,777,787,797,808
818,828,838,848,858,868,878,888,898,909
919,929,939,949,959,969,979,989,999,1001
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
0

Using RxJava

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;

public class Palindro {
    private static boolean isPalindrome(int x) {
        String s1 = String.valueOf(x);
        StringBuilder r1 = new StringBuilder(s1).reverse();
        return r1.toString().equals(s1);
    }

    public static void main(String[] args) {
        Observable.range(11, Integer.MAX_VALUE - 10)
                  .filter(x -> isPalindrome(x))
                  .take(100)
                  .subscribe(new Printer());
    }
}

class Printer implements Consumer<Integer> {
    private int counter;

    @Override
    public void accept(Integer t) throws Throwable {
        if (counter % 10 == 0) {
            System.out.println();
        }
        System.out.printf("%d  ", t);
        counter++;
    }
}

Just change the parameter to method take if you want less than or more than the first 100 number palindromes.

Abra
  • 19,142
  • 7
  • 29
  • 41
0

Here is an easy way using streams.

  • iterate sequential integers starting with 11
  • convert to a string
  • only pass those that equal their reverse
  • limit to the first 100
  • collect in a list.
  • print
List<String> results = IntStream.iterate(11,i->i+1)
        .mapToObj(Integer::toString)
        .filter(a -> a.equals(
                new StringBuilder(a).reverse().toString()))
        .limit(100).collect(Collectors.toList());

for(int i = 0; i < results.size(); i+= 10) {
    System.out.println(results.subList(i,i+10));
}

Prints

[11, 22, 33, 44, 55, 66, 77, 88, 99, 101]
[111, 121, 131, 141, 151, 161, 171, 181, 191, 202]
[212, 222, 232, 242, 252, 262, 272, 282, 292, 303]
[313, 323, 333, 343, 353, 363, 373, 383, 393, 404]
[414, 424, 434, 444, 454, 464, 474, 484, 494, 505]
[515, 525, 535, 545, 555, 565, 575, 585, 595, 606]
[616, 626, 636, 646, 656, 666, 676, 686, 696, 707]
[717, 727, 737, 747, 757, 767, 777, 787, 797, 808]
[818, 828, 838, 848, 858, 868, 878, 888, 898, 909]
[919, 929, 939, 949, 959, 969, 979, 989, 999, 1001]
WJS
  • 36,363
  • 4
  • 24
  • 39