# Palindromic numbers with a binary twist

Warning : this is NOT a "hey, let's draw a cake in ASCII-art" challenge! Please keep reading ;)

Some time ago it was my birthday, I'm 33 now.

So there is this awkward social tradition consisting in inviting family and friends, putting number-like candles on a cake, sing songs and open gifts.

   33
--------


Instead of numbers, I can use the binary system to put standard candles: I place 6 of them on the cake and light two of them.

 100001
--------


I can see that both decimal and binary numbers of my age are palindromic!

# Challenge

I want to know if any other number can be put on a cake with candles and be palindromic, decimal and binary.

Write a program/function to test if a number is palindromic in both decimal and binary. But wait, there's more : in binary, leading zeros count for the test!

## Input

A decimal number x that I want to test if it is birthday palindromic with 0 < x < 232-1 (yes, the people in my dimension live very long)

## Output

Truthy if it meets exactly these two conditions, Falsey else:

• The decimal representation of the number is a standard palindrome
• The binary representation of the number is a standard palindrome, and adding leading zeros may help with this

## Test cases

1 > 1 => Truthy
6 > 110 (0110) => Truthy
9 > 1001 => Truthy
10 > 1010 (01010) => Falsey, 10 is not palindromic
12 => 1100 (001100) => Falsey, 12 is not palindromic
13 => 1101 (...01101) => Falsey, neither 13 nor 1101 are palindromic
14 => 1110 (01110) => Falsey, 14 is not palindromic
33 > 100001 => Truthy
44 > 101100 (..0101100) => Falsey, 101100 is not palindromic
1342177280 > 1010000000000000000000000000000 (00000000000000000000000000001010000000000000000000000000000) => Falsey, 1342177280 is not palindromic (but the binary representation is)
297515792 > 10001101110111011101100010000 (000010001101110111011101100010000) => Truthy


## Rules

Good luck, and eventually happy birthday!

• Sandbox – Goufalite Aug 16 '17 at 5:58
• Might want to change the title as the birthday part is irrelavent. – NoOneIsHere Aug 16 '17 at 6:00
• @NoOneIsHere well the challenge is about candles on a birthday cake. Also there's the twist on the binary representation so it's not "generic palindromic numbers". If your comment is upvoted I'll come up with another title. – Goufalite Aug 16 '17 at 6:06
• So, according to the rules, 0b01010000000000000000000000000000 is not palindromic since it would require more zeroes to be added and thus exceed 2^32-1? In this case it would help to add something like 1342177280 as a falsey test case. – Cristian Lupascu Aug 16 '17 at 11:54
• @w0lf I didn't write a limit for adding zeros but I understand your stack overflow problem ;) Furthermore, 1342177280 is not decimal palindromic so Falsey. Editing – Goufalite Aug 16 '17 at 12:07

# 05AB1E, 7 bytes

b0Ü‚DíQ


Try it online! or as a Test Suite

Explanation

b         # convert input to binary
0Ü       # remove trailing zeroes
‚      # pair with input
D     # duplicate
í    # reverse each (in the copy)
Q   # check for equality

• Bifurcate didn't help? – Magic Octopus Urn Aug 17 '17 at 21:08
• @MagicOctopusUrn: Unfortunately not, as I want to reverse each number in the list and not the list itself. – Emigna Aug 17 '17 at 21:10

# Python 3, 59 bytes

lambda a:all(c==c[::-1]for c in[str(a),bin(a).strip('0b')])


Try it online!

-3 bytes thanks to Rod
-3 bytes thanks to Connor Johnston

# JavaScript (ES6), 65 bytes

Returns 0 or 1.

n=>(g=b=>[...s=n.toString(b)].reverse().join==s)()&g(2,n/=n&-n)


### How?

The helper function g() takes an integer b as input and tests whether n is a palindrome in base b. If b is not specified, it just converts n to a string before testing it.

We get rid of the trailing zeros in the binary representation of n by isolating the least significant 1 with n&-n and dividing n by the resulting quantity.

Fun fact: it's truthy for 0 because (0/0).toString(2) equals "NaN", which is a palindrome. (But 0 is not a valid input anyway.)

### Test cases

let f =

n=>(g=b=>[...s=n.toString(b)].reverse().join==s)()&g(2,n/=n&-n)

console.log(f(1 )) // Truthy
console.log(f(6 )) // Truthy
console.log(f(9 )) // Truthy
console.log(f(10)) // Falsey
console.log(f(12)) // Falsey
console.log(f(13)) // Falsey
console.log(f(14)) // Falsey
console.log(f(33)) // Truthy
console.log(f(44)) // Falsey

# Mathematica, 52 49 bytes

i=IntegerReverse;i@#==#&&!i[#,2,Range@#]~FreeQ~#&


Try it on Wolfram Sandbox

### Usage

f = (i=IntegerReverse;i@#==#&&!i[#,2,Range@#]~FreeQ~#&);


f[6]


True

f /@ {9, 14, 33, 44}


{True, False, True, False}

### Explanation

i=IntegerReverse;i@#==#&&!i[#,2,Range@#]~FreeQ~#&

i=IntegerReverse                                   (* Set i to the integer reversing function. *)
i@#==#                            (* Check whether the input reversed is equal to input. *)
&&                          (* Logical AND *)
i[#,2,Range@#]           (* Generate the binary-reversed versions of input, whose lengths *)
(* (in binary) are {1..<input>} *)
(* trim or pad 0s to match length *)
~FreeQ~#   (* Check whether the result is free of the original input *)
!                         (* Logical NOT *)


### Version with builtin PalindromeQ

PalindromeQ@#&&!IntegerReverse[#,2,Range@#]~FreeQ~#&


# Pyth - 13 bytes

&_I.s.BQZ_I

• You can use _MI and jQ2 to save 2 bytes: _MI,.sjQ2Z – Erik the Outgolfer Aug 16 '17 at 10:26

# Japt, 14 bytes

s ê¬©¢w n2 ¤ê¬


Test it online!

### Explanation

 s ê¬ © ¢   w n2 ¤  ê¬
Us êq &&Us2 w n2 s2 êq   Ungolfed
Implicit: U = input integer
Us êq                    Convert U to a string and check if it's a palindrome.
Us2 w            Convert U to binary and reverse.
n2 s2      Convert to a number, then back to binary, to remove extra 0s.
êq   Check if this is a palindrome.
&&                 Return whether both of these conditions were met.

• Came up with a couple of similar solutions for 13 bytes: sêQ *(Â¢w)sêQ and sêQ &¢w n sêQ – Shaggy Feb 15 '18 at 12:20
• @Shaggy Thanks, but unfortunately those both fail on 297515792 (the reversed binary converted to decimal is just too big for JS to handle)... – ETHproductions Feb 15 '18 at 13:47

# Proton, 57 bytes

a=>(b=c=>c==c[to by-1])(str(a))*b(bin(a)[2to].strip('0'))


Try it online!

# Jelly, 8 bytes

Bt0ŒḂaŒḂ


Try it online!

• You probably want ȧ or a instead of µ because otherwise this will always be truthy. – Erik the Outgolfer Aug 16 '17 at 10:20
• @EriktheOutgolfer whoops thanks – hyper-neutrino Aug 16 '17 at 15:29

# APL, 27 31 Bytes

∧/(⌽≡⊢)∘⍕¨{⍵,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢⍵}


How's it work? Using 6 as the argument...

      2⊥⍣¯1⊢6 ⍝ get the bit representation
1 1 0

⌽2⊥⍣¯1⊢6 ⍝ reverse it (if it's a palindrome, it doesn't matter)
0 1 1

{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6 ⍝ drop off the trailing (now leading 0's)
1 1

6,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6 ⍝ enclose and concatenate the bits to the original number
┌─┬───┐
│6│1 1│
└─┴───┘

(⌽≡⊢)∘⍕ ⍝ is a composition of
⍕ ⍝ convert to string and
(⌽≡⊢) ⍝ palindrome test

(⌽≡⊢)∘⍕¨6,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6 ⍝ apply it to each of the original argument and the bit representation
1 1

∧/(⌽≡⊢)∘⍕¨6,⊂{⍵/⍨∨\⍵}⌽2⊥⍣¯1⊢6  ⍝ ∧/ tests for all 1's (truth)
1


Try it on TryAPL.org

• According to the specs, 6 is supposed to be a good input, but the expression provided return false. – lstefano Aug 17 '17 at 6:55
• Ah, rats! That's what I get for not reading the problem in its entirety. Good catch. thank you! I've amended with a slightly longer, but hopefully more correct, solution. – Brian Aug 17 '17 at 9:23
• Welcome to PPCG. Nice first post! Unfortunately, your submission in its current form is neither a program, nor a function. No worries though, you can make it into a function but letting the outer braces enclose the entire code. – Adám Aug 17 '17 at 10:42
• Save three bytes: {(⌽¨≡⊢)⍕¨⍵,⊂(⌽↓⍨~⊥~)2⊥⍣¯1⊢⍵} (it is good form to provide a link to run the entire test suite) – Adám Aug 17 '17 at 10:45

# Brachylog, 7 bytes

↔?ḃc↔.↔


Try it online!

That's a lot of ↔'s…

### Explanation

With the implicit input and output, the code is: ?↔?ḃc↔.↔.

?↔?        The Input is a palindrome
ḃ       Convert it to the list of its digits in binary
c      Concatenate it into an integer
↔     Reverse it: this causes to remove the trailing 0's
.↔.  The resulting number is also a palindrome


# APL (Dyalog Classic), 26 bytes

{≡∘⌽⍨⍕⍵,⍵,⍨(<\⊂⊢)⌽2⊥⍣¯1⊢⍵}


## Explanation

                  2⊥⍣¯1⊢⍵  encode ⍵ as binary
⌽         reverse
(<\⊂⊢)          partition from first 1
⍵,⍵,⍨                prepend and append ⍵
⍕                     turn into text string
≡∘⌽⍨                       match text with its reverse (f⍨X is XfX, where f is a composed function that reverses its right argument and matches with left)


Try it online!

• Ooh, you out-golfed BB! – Adám Aug 22 '17 at 15:38

# Perl, 53 +3 (-pal) bytes

$_=sprintf"%b",$_;s/0+$//;$_="$_/@F"eq reverse"@F/$_"


try it online

# Octave, 68 66 bytes

@(x)all([d=num2str(x) b=deblank(['' dec2bin(x)-48])]==flip([b d]))


Try it online!

Initial offering from Octave.

We basically create an array containing the number as a decimal string and the number as a binary string with trailing 0's removed. Then we create an array with the same to strings but with the binary and decimal numbers flipped. Finally both arrays are compared and the result is either true if they match (both palindromes) or false if they don't (one or both not palindromes).

• Save 2 bytes using flip instead of fliplr.

# Pyt, 10 bytes

Returns [1] if true, [0] if false

ĐɓƖ₫áĐ₫=ʁ∧


Try it online!

Explanation:

              Implicit input
Đ             Duplicate input
ɓ             Get input in binary (as string)
Ɩ             Cast to integer
₫             Reverse the digits (this removes any trailing zeroes)
á             Push the stack into a list
Đ             Duplicate the list
₫             Reverse the digits of each element of the list
=             Are the two lists equal element-wise
ʁ∧            Reduce the list by bitwise AND


# Retina, 72 bytes

.+
$*_;$&
+(_+)\1
$+0 0_ _ 0+; ; +\b(\w)((\w*)\1)?\b$3
(\B;\B)|.*
$.1  Try it online! Link includes test cases. Works by creating a unary duplicate of the original number, but using _s so that it's not confused by e.g. an input of 11. The unary number is then converted to "binary" and trailing zeros stripped. Palindromes then get successively truncated and the last stage tests whether there is anything left. # Mathematica, 70 bytes (P=PalindromeQ)[PadRight[#~IntegerDigits~2,#~IntegerExponent~2]]&&P@#&  # Husk, 14 bytes ¤&S=↔ȯ↓=0↔ḋ⁰d⁰  Try it online! ### Ungolfed/Explanation  d⁰ -- digits of input in decimal ḋ⁰) -- digits of input in binary ↔ -- reverse (↓=0 -- and drop all leading zeros ¤& -- test the two lists if S=↔ -- they're equal to their own reverse  # Gaia, 10 bytes ṙṭ@ḍ2⁻Πbṭ∧  Try it online! ### Explanation Instead of checking with leading zeroes in binary, I check without without the trailing zeros. ṙ String representation of number ṭ Is palindromic? @ Push input again ḍ Prime factors 2⁻ Remove all 2s Π Product b Convert to binary ṭ Is palindromic? ∧ Logical and  # C (gcc), 105 bytes r(n,b){int s=0,c=n;for(;n;n/=b)s=s*b+n%b;return s==c;} c;f(n){for(c=n;c%2<1;c/=2);return r(n,10)&r(c,2);}  Try it online! • You can replace both occurrences of return  with n=. (95 bytes.) – Jonathan Frech Sep 19 '17 at 7:17 • And you can remove the new line for an additional byte saved. – Jonathan Frech Sep 19 '17 at 9:58 # C# (.NET Core), 130 129 179 173 + 23 bytes a few things, thank you to Ed Marty for pointing out that i need to check for as many 0's padded in front for a palindrome. And i need to make sure that i can check up to x^32-1. x=>{var a=Convert.ToString(x,2);var b=x+"";Func<string,bool>p=z=>z.SequenceEqual(z.Reverse());return new int[a.Length].Select((_,z)=>p(new string('0',z)+a)).Any(z=>z)&p(b);}  Try it online! • You can remove the space between return and ( for 129 bytes – Mr. Xcoder Aug 16 '17 at 7:31 • This only works when adding at most one leading 0, but the problem specifies multiple leading zeros are allowed. – Ed Marty Aug 16 '17 at 16:07 • @EdMarty that has been handle, as well as the stack overflow bug. – Dennis.Verweij Aug 16 '17 at 20:12 • you are missing a using System; and using System.Linq – LiefdeWen Aug 17 '17 at 11:22 • or is that the +23 bytes? – LiefdeWen Aug 17 '17 at 11:23 # Python 2, 56 bytes lambda n:all(s==s[::-1]for s in(n,bin(n).strip("0b")))  Try it online! Uses Python's strip method to both remove the bin(..)'s output's leading 0b and the binary number's trailing zeros (as they will always have a matching bit). # Pyth, 25221918 17 bytes -3 6 7 8 bytes by learning the language further Ks_.Bsz&_IzqKs_K  Explanation: Ks Set K to the integer version of... _.BsJ Reverse string of the binary input & And _Iz Is the input equal to the reverse of itself? qKs_K Is K equal to int(the reverse of basically string(K))  I am sure that this can be golfed down, I'll be working on that. Test Suite # PHP, 69+1 bytes $q=trim(decbin($p=$argn),0);if(strrev($p)==$p&&strrev($q)==$q)echo$p;  Run as pipe with -nR Echoes the original input for truthy / nothing for falsey Try it online! # APL2 (not Dyalog), 36 bytes (N≡⌽N←⍕N)^∨/(((⌽B)⍳1)↓B)⍷B←(32⍴2)⊤N←  First let B be the 32-bit representation of N: B←(32⍴2)⊤N  Then mirror B and find the position of the 1st 1: (⌽B)⍳1  Then drop that many positions from B. This will preserve the correct number of leading 0s. Then perform FIND and an OR-REDUCTION to see if the cropped B contains its own mirror. Now let's look at N, the decimal. The left-most bracketed expression converts N to a character vector and checks if it MATCHes its own mirror. Finally, an AND joins the two checks. In APL2 I can't make a neat lambda so I wrote a one-liner and included the assignment arrow. Hope this isn't cheating. • Welcome to PPCG! – Martin Ender Feb 15 '18 at 12:28 • Welcome to PPCG! For a less cheating version, are you able to append a quad (⎕) to make it a full program instead? Also, are you able to shorten to (N≡⌽N←⍕N)^∨/(B↓⍨1⍳⍨⌽B)⍷B←(32⍴2)⊤N←⎕? – Erik the Outgolfer Feb 15 '18 at 12:47 • Erik, thanks for checking! I'm sure this could be improved, but I don't have the ⍨ squiggle in APL2. – mappo Feb 15 '18 at 12:57 # Java 8, 105 104 bytes n->{String t=n+n.toString(n,2).replaceAll("0*$","")+n;return t.contains(new StringBuffer(t).reverse());}


Explanation:

Try it here.

n->{                         // Method with Integer parameter and boolean return-type
String t=n                 //  Create a String t starting with the input Integer
+n.toString(n,2)         //  Append the binary representation of the input Integer,
.replaceAll("0*\$","")  //   with all trailing zeroes removed
+n;                      //  Append the input Integer again
return t.contains(new StringBuffer(t).reverse());
//  Return true if t is a palindrome
}                            // End of method
`