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
- Standard loopholes are disallowed
- Built-in library conversions and tests are allowed
- This is code-golf, the shortest code win!
Good luck, and eventually happy birthday!
25 Answers 25
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
-
\$\begingroup\$ Bifurcate didn't help? \$\endgroup\$Magic Octopus Urn– Magic Octopus Urn2017年08月17日 21:08:36 +00:00Commented Aug 17, 2017 at 21:08
-
\$\begingroup\$ @MagicOctopusUrn: Unfortunately not, as I want to reverse each number in the list and not the list itself. \$\endgroup\$Emigna– Emigna2017年08月17日 21:10:31 +00:00Commented Aug 17, 2017 at 21:10
Python 3, 59 bytes
lambda a:all(c==c[::-1]for c in[str(a),bin(a).strip('0b')])
-3 bytes thanks to Rod
-3 bytes thanks to Connor Johnston
-
1\$\begingroup\$ you can swap the double lambda with list comprehension \$\endgroup\$Rod– Rod2017年08月16日 11:42:05 +00:00Commented Aug 16, 2017 at 11:42
-
1\$\begingroup\$ using strip with strings will remove single characters: [bin(a)[2:].strip('0') => bin(a).strip('0b')](tio.run/… "Python 3 – Try It Online") \$\endgroup\$Conner Johnston– Conner Johnston2017年08月16日 20:00:45 +00:00Commented Aug 16, 2017 at 20:00
-
\$\begingroup\$ @ConnerJohnston o cool, thanks! \$\endgroup\$2017年08月16日 20:07:30 +00:00Commented Aug 16, 2017 at 20:07
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~#&
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~#&
-
\$\begingroup\$ You can use
_MI
andjQ2
to save 2 bytes:_MI,.sjQ2Z`
\$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年08月16日 10:26:13 +00:00Commented Aug 16, 2017 at 10:26
-
\$\begingroup\$ You probably want
ȧ
ora
instead ofµ
because otherwise this will always be truthy. \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2017年08月16日 10:20:57 +00:00Commented Aug 16, 2017 at 10:20 -
\$\begingroup\$ @EriktheOutgolfer whoops thanks \$\endgroup\$2017年08月16日 15:29:45 +00:00Commented Aug 16, 2017 at 15:29
Japt, 14 bytes
s ꬩ¢w n2 ¤ê¬
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.
-
\$\begingroup\$ Came up with a couple of similar solutions for 13 bytes:
sêQ *(¢w)sêQ
andsêQ &¢w n sêQ
\$\endgroup\$Shaggy– Shaggy2018年02月15日 12:20:48 +00:00Commented Feb 15, 2018 at 12:20 -
\$\begingroup\$ @Shaggy Thanks, but unfortunately those both fail on
297515792
(the reversed binary converted to decimal is just too big for JS to handle)... \$\endgroup\$ETHproductions– ETHproductions2018年02月15日 13:47:18 +00:00Commented Feb 15, 2018 at 13:47
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
-
\$\begingroup\$ According to the specs, 6 is supposed to be a good input, but the expression provided return false. \$\endgroup\$lstefano– lstefano2017年08月17日 06:55:59 +00:00Commented Aug 17, 2017 at 6:55
-
\$\begingroup\$ 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. \$\endgroup\$Brian– Brian2017年08月17日 09:23:31 +00:00Commented Aug 17, 2017 at 9:23
-
\$\begingroup\$ 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. \$\endgroup\$Adám– Adám2017年08月17日 10:42:08 +00:00Commented Aug 17, 2017 at 10:42
-
\$\begingroup\$ Save three bytes:
{(⌽¨≡⊢)⍕¨⍵,⊂(⌽↓⍨~⊥~)2⊥⍣¯1⊢⍵}
(it is good form to provide a link to run the entire test suite) \$\endgroup\$Adám– Adám2017年08月17日 10:45:30 +00:00Commented Aug 17, 2017 at 10:45
Brachylog, 7 bytes
↔?ḃc↔.↔
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)
-
\$\begingroup\$ Ooh, you out-golfed BB! \$\endgroup\$Adám– Adám2017年08月22日 15:38:47 +00:00Commented Aug 22, 2017 at 15:38
Octave, (削除) 68 (削除ここまで) 66 bytes
@(x)all([d=num2str(x) b=deblank(['' dec2bin(x)-48])]==flip([b d]))
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 offliplr
.
Pyt, 10 bytes
Returns [1] if true, [0] if false
ĐɓƖ₫áĐ₫=ʁ∧
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↔ḋ0d0
Ungolfed/Explanation
d0 -- digits of input in decimal
ḋ0) -- 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ṭ∧
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);}
-
\$\begingroup\$ You can replace both occurrences of
return
withn=
. (95 bytes.) \$\endgroup\$Jonathan Frech– Jonathan Frech2017年09月19日 07:17:38 +00:00Commented Sep 19, 2017 at 7:17 -
\$\begingroup\$ And you can remove the new line for an additional byte saved. \$\endgroup\$Jonathan Frech– Jonathan Frech2017年09月19日 09:58:00 +00:00Commented Sep 19, 2017 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);}
-
1\$\begingroup\$ You can remove the space between
return
and(
for 129 bytes \$\endgroup\$Mr. Xcoder– Mr. Xcoder2017年08月16日 07:31:50 +00:00Commented Aug 16, 2017 at 7:31 -
\$\begingroup\$ This only works when adding at most one leading 0, but the problem specifies multiple leading zeros are allowed. \$\endgroup\$Ed Marty– Ed Marty2017年08月16日 16:07:57 +00:00Commented Aug 16, 2017 at 16:07
-
\$\begingroup\$ @EdMarty that has been handle, as well as the stack overflow bug. \$\endgroup\$Dennis.Verweij– Dennis.Verweij2017年08月16日 20:12:00 +00:00Commented Aug 16, 2017 at 20:12
-
\$\begingroup\$ you are missing a
using System;
andusing System.Linq
\$\endgroup\$LiefdeWen– LiefdeWen2017年08月17日 11:22:41 +00:00Commented Aug 17, 2017 at 11:22 -
\$\begingroup\$ or is that the +23 bytes? \$\endgroup\$LiefdeWen– LiefdeWen2017年08月17日 11:23:28 +00:00Commented Aug 17, 2017 at 11:23
Python 2, 56 bytes
lambda n:all(s==s[::-1]for s in(`n`,bin(n).strip("0b")))
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, (削除) 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.
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
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.
-
1\$\begingroup\$ Welcome to PPCG! \$\endgroup\$Martin Ender– Martin Ender2018年02月15日 12:28:13 +00:00Commented Feb 15, 2018 at 12:28
-
\$\begingroup\$ 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←⎕
? \$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2018年02月15日 12:47:58 +00:00Commented Feb 15, 2018 at 12:47 -
\$\begingroup\$ Erik, thanks for checking! I'm sure this could be improved, but I don't have the ⍨ squiggle in APL2. \$\endgroup\$mappo– mappo2018年02月15日 12:57:22 +00:00Commented Feb 15, 2018 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:
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
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 like1342177280
as a falsey test case. \$\endgroup\$1342177280
is not decimal palindromic so Falsey. Editing \$\endgroup\$