Palindromic numbers with a binary twist

29

1

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!

Goufalite

Posted 2017-08-16T05:58:36.757

Reputation: 391

Sandbox – Goufalite – 2017-08-16T05:58:59.943

6Might want to change the title as the birthday part is irrelavent. – NoOneIsHere – 2017-08-16T06:00:19.357

@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 – 2017-08-16T06:06:39.380

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 – 2017-08-16T11:54:11.447

1@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 – 2017-08-16T12:07:39.927

@Goufalite You are right, of course. A better example would be 297515792 (10001101110111011101100010000 in binary) – Cristian Lupascu – 2017-08-16T12:31:08.303

Ok, adding the test case. I suppose it is no more a problem since everyone here trim the trailing zeros instead of appending them for the test ;) – Goufalite – 2017-08-16T12:37:27.073

Answers

17

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

Emigna

Posted 2017-08-16T05:58:36.757

Reputation: 50 798

Bifurcate didn't help? – Magic Octopus Urn – 2017-08-17T21:08:36.153

@MagicOctopusUrn: Unfortunately not, as I want to reverse each number in the list and not the list itself. – Emigna – 2017-08-17T21:10:31.510

11

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

HyperNeutrino

Posted 2017-08-16T05:58:36.757

Reputation: 26 575

1you can swap the double lambda with list comprehension – Rod – 2017-08-16T11:42:05.597

1

using strip with strings will remove single characters: bin(a)[2:].strip('0') => bin(a).strip('0b')

– Conner Johnston – 2017-08-16T20:00:45.330

@ConnerJohnston o cool, thanks! – HyperNeutrino – 2017-08-16T20:07:30.707

8

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

Arnauld

Posted 2017-08-16T05:58:36.757

Reputation: 111 334

5

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~#&

JungHwan Min

Posted 2017-08-16T05:58:36.757

Reputation: 13 290

4

Pyth - 13 bytes

&_I.s.BQ`Z_I`

Test Suite.

Maltysen

Posted 2017-08-16T05:58:36.757

Reputation: 25 023

You can use _MI and jQ2 to save 2 bytes: `_MI,.sjQ2Z`` – Erik the Outgolfer – 2017-08-16T10:26:13.353

3

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.

ETHproductions

Posted 2017-08-16T05:58:36.757

Reputation: 47 880

Came up with a couple of similar solutions for 13 bytes: sêQ *(¢w)sêQ and sêQ &¢w n sêQ

– Shaggy – 2018-02-15T12:20:48.850

@Shaggy Thanks, but unfortunately those both fail on 297515792 (the reversed binary converted to decimal is just too big for JS to handle)... – ETHproductions – 2018-02-15T13:47:18.037

2

Proton, 57 bytes

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

Try it online!

HyperNeutrino

Posted 2017-08-16T05:58:36.757

Reputation: 26 575

2

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

Brian Becker

Posted 2017-08-16T05:58:36.757

Reputation: 21

According to the specs, 6 is supposed to be a good input, but the expression provided return false. – lstefano – 2017-08-17T06:55:59.013

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 Becker – 2017-08-17T09:23:31.217

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 – 2017-08-17T10:42:08.590

Save three bytes: {(⌽¨≡⊢)⍕¨⍵,⊂(⌽↓⍨~⊥~)2⊥⍣¯1⊢⍵} (it is good form to provide a link to run the entire test suite)

– Adám – 2017-08-17T10:45:30.220

1

Jelly, 8 bytes

Bt0ŒḂaŒḂ

Try it online!

HyperNeutrino

Posted 2017-08-16T05:58:36.757

Reputation: 26 575

You probably want ȧ or a instead of µ because otherwise this will always be truthy. – Erik the Outgolfer – 2017-08-16T10:20:57.753

@EriktheOutgolfer whoops thanks – HyperNeutrino – 2017-08-16T15:29:45.970

1

Perl, 53 +3 (-pal) bytes

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

try it online

Nahuel Fouilleul

Posted 2017-08-16T05:58:36.757

Reputation: 5 582

1

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

Fatalize

Posted 2017-08-16T05:58:36.757

Reputation: 32 976

1

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!

Gil

Posted 2017-08-16T05:58:36.757

Reputation: 141

Ooh, you out-golfed BB! – Adám – 2017-08-22T15:38:47.020

1

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

mudkip201

Posted 2017-08-16T05:58:36.757

Reputation: 833

0

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!

Dennis.Verweij

Posted 2017-08-16T05:58:36.757

Reputation: 101

1

You can remove the space between return and ( for 129 bytes

– Mr. Xcoder – 2017-08-16T07:31:50.263

This only works when adding at most one leading 0, but the problem specifies multiple leading zeros are allowed. – Ed Marty – 2017-08-16T16:07:57.277

@EdMarty that has been handle, as well as the stack overflow bug. – Dennis.Verweij – 2017-08-16T20:12:00.400

you are missing a using System; and using System.Linq – LiefdeWen – 2017-08-17T11:22:41.977

or is that the +23 bytes? – LiefdeWen – 2017-08-17T11:23:28.587

@LiefdeWen my namespace is System.linq, and that's the +23 bytes. – Dennis.Verweij – 2017-08-17T11:24:58.423

0

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.

Neil

Posted 2017-08-16T05:58:36.757

Reputation: 95 035

0

Mathematica, 70 bytes

(P=PalindromeQ)[PadRight[#~IntegerDigits~2,#~IntegerExponent~2]]&&P@#&

J42161217

Posted 2017-08-16T05:58:36.757

Reputation: 15 931

0

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

ბიმო

Posted 2017-08-16T05:58:36.757

Reputation: 15 345

0

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

Business Cat

Posted 2017-08-16T05:58:36.757

Reputation: 8 927

0

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!

Leaky Nun

Posted 2017-08-16T05:58:36.757

Reputation: 45 011

You can replace both occurrences of return with n=. (95 bytes.)

– Jonathan Frech – 2017-09-19T07:17:38.877

And you can remove the new line for an additional byte saved. – Jonathan Frech – 2017-09-19T09:58:00.920

0

Pyth, 25 22 19 18 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

Stan Strum

Posted 2017-08-16T05:58:36.757

Reputation: 436

0

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).

Jonathan Frech

Posted 2017-08-16T05:58:36.757

Reputation: 6 681

0

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

Kevin Cruijssen

Posted 2017-08-16T05:58:36.757

Reputation: 67 575

0

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!

Jo.

Posted 2017-08-16T05:58:36.757

Reputation: 974

0

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.

Tom Carpenter

Posted 2017-08-16T05:58:36.757

Reputation: 3 990

0

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.

mappo

Posted 2017-08-16T05:58:36.757

Reputation: 101

1Welcome to PPCG! – Martin Ender – 2018-02-15T12:28:13.530

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 – 2018-02-15T12:47:58.407

Erik, thanks for checking! I'm sure this could be improved, but I don't have the ⍨ squiggle in APL2. – mappo – 2018-02-15T12:57:22.200