Camel
Peter
Peter Campbell Smith

Binary knight

Weekly challenge 118 — 21 June 2021

Week 118: 21 Jun 2021

Task 1

Task — Binary palindrome

You are given a positive integer $N. Write a script to find out if the binary representation of the given integer is a palindrome. Print 1 if it is, otherwise 0.

Examples


Input: $N = 5
Output: 1 as binary representation of 5 is 101 which is 
   a palindrome.

Input: $N = 4
Output: 0 as binary representation of 4 is 100 which is 
   NOT a palindrome.

Analysis

The sprintf function converts an integer to its binary representation, and reverse reverses it. Then it's just a case of comparing these two strings and outputting the result neatly.

Try it 

Try running the script with any input:



example: 127

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-06-21
use utf8;     # Week 118 - task 1 - Binary palindrome
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

binary_palindrome(5);
binary_palindrome(4);
binary_palindrome(12345);
binary_palindrome(2 ** 16 + 1);
binary_palindrome(96198381);

sub binary_palindrome {
    
    my ($j, $bin, $output, $nib, $l);
    
    # reverse binary string
    $j = $_[0];
    $bin = sprintf('%b', $j);
    $nib = reverse($bin);
    
    # report
    $l = ' ' x (length($j) - 1);
    printf(qq[\nInput:  %d = %s], $j, $bin);
    printf(qq[\nOutput: %s%s : %s\n], $l, ($bin eq $nib ? '1' : '0'), $nib);
}


last updated 2026-03-17 — 8 lines of code

Output


Input:  5 = 101
Output: 1 : 101

Input:  4 = 100
Output: 0 : 001

Input:  12345 = 11000000111001
Output:     0 : 10011100000011

Input:  65537 = 10000000000000001
Output:     1 : 10000000000000001

Input:  96198381 = 101101110111101111011101101
Output:        1 : 101101110111101111011101101

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain