18
\$\begingroup\$

Write a full program to find whether the binary representation of a number is palindrome or not?

Sample Input
5

Sample Output
YES

Print YES if binary representation is palindrome and NO otherwise.

\$\endgroup\$
6
  • \$\begingroup\$ What should be the output when it's not a palindrome? \$\endgroup\$
    – Dogbert
    Feb 8 '11 at 15:20
  • \$\begingroup\$ @dogbert It should be 'NO' without the quotes. \$\endgroup\$
    – fR0DDY
    Feb 8 '11 at 15:22
  • 1
    \$\begingroup\$ How do you know it's a palindrome? Because the values from the first nonzero to the end of the "string" are palindromic? This smells really bad to me, as a challenge. \$\endgroup\$
    – jcolebrand
    Feb 9 '11 at 23:40
  • 1
    \$\begingroup\$ Much as I <3 gnibbler's answer, it's not actually the shortest solution, and any question tagged [code-golf] should pick the shortest solution as the winner. \$\endgroup\$ Feb 10 '11 at 3:48
  • \$\begingroup\$ Input is given how? \$\endgroup\$
    – Joey
    Mar 2 '11 at 8:34

30 Answers 30

28
\$\begingroup\$

Python - 46 chars

n=bin(input())[2:]
print'YNEOS'[n!=n[::-1]::2]
\$\endgroup\$
3
  • \$\begingroup\$ Wow. What does [n!=n[::-1]::2] do? \$\endgroup\$
    – Dogbert
    Feb 8 '11 at 21:38
  • 2
    \$\begingroup\$ @Dogbert, n[::-1] is a slice. The start and end indexs are empty, so it means the whole string. The stepsize is -1, so when you see [::-1] it is a short way to reverse a string/list etc. So n!=n[::-1] is True (ie 1) when n is not a palindrome. Therefore when n is a palindrome, you get 'YNEOS'[0::2] - start at 0 and take every 2nd character. When n is not a palindrome you get 'YNEOS'[1::2] - start at 1 and take every second character :) \$\endgroup\$
    – gnibbler
    Feb 8 '11 at 22:22
  • \$\begingroup\$ I think people are voting for the slice trick :), rightly so. :P +1 \$\endgroup\$
    – st0le
    Feb 9 '11 at 6:08
5
\$\begingroup\$

Golfscript -- 22 chars

~2base.-1%="YES""NO"if
\$\endgroup\$
4
\$\begingroup\$

Ruby, 41 39

$><<%w(YES NO)[(n="%b"%$*)<=>n.reverse]

Thanks to Michael Kohl's "%b"%gets trick.

\$\endgroup\$
1
  • \$\begingroup\$ Very nice, I like this a lot! +1 for using the spaceship in a creative way :-) \$\endgroup\$ Mar 6 '11 at 17:23
4
\$\begingroup\$

C 84 81 74 Characters

r;main(v,x){for(scanf("%d",&v),x=v;v;v/=2)r=r*2|v&1;puts(r-x?"NO":"YES");}

It does not use any function like string reverse.

\$\endgroup\$
4
  • \$\begingroup\$ Couldn't you save a few characters changing r<<=1 into r*=2, v>>=1 into v/=2 and {} into ;? \$\endgroup\$
    – user56228
    Sep 23 '16 at 13:20
  • \$\begingroup\$ @paxdiablo Indeed. Changed. Thanks a lot. \$\endgroup\$
    – fR0DDY
    Sep 24 '16 at 7:48
  • \$\begingroup\$ r*=2,r|=v&1 -> r=r*2|v&1 (-2) \$\endgroup\$
    – Titus
    Sep 24 '16 at 13:00
  • \$\begingroup\$ and moving that term to the body of the loop saves another byte. \$\endgroup\$
    – Titus
    Sep 24 '16 at 13:01
3
\$\begingroup\$

Javascript - 79 77 chars

alert((a=(prompt()*1).toString(2))-a.split("").reverse().join("")?"NO":"YES")

More information

prompt()*1 : Quick trick to convert string to number.

.toString(2) : That's how you convert to binary in javascript.

a.split("").reverse().join("") : There is no native support to reverse string, so you have to convert string to array and array to string.

("[part1]" - "[part 2]")?"YES":"NO" : - is a replacement for != to save 1 char.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Excellent explanation. \$\endgroup\$
    – TehShrike
    Mar 3 '11 at 1:44
2
\$\begingroup\$

PHP - 41

<?=strrev($n=decbin(`cat`))==$n?@YES:@NO;

Test:

php 713.php <<< 5
YES
php 713.php <<< 6
NO
\$\endgroup\$
2
  • 4
    \$\begingroup\$ If you're going to use shell calls to get the input, might as well use m4 instead of cat to save one. There's also pg and dd (which writes some bytes to stderr). \$\endgroup\$
    – Nabb
    Feb 8 '11 at 15:34
  • \$\begingroup\$ Have You tried that on Windows? ;) \$\endgroup\$
    – Titus
    Sep 24 '16 at 13:19
2
\$\begingroup\$

Perl, 45 characters

$_=sprintf'%b',shift;
print reverse==$_?YES:NO
\$\endgroup\$
2
\$\begingroup\$

Ruby, 43 characters

puts((n="%b"%gets)==n.reverse ? "YES":"NO")
\$\endgroup\$
1
  • \$\begingroup\$ Save 2: puts (n="%b"%gets)==n.reverse ? :YES: :NO \$\endgroup\$
    – Phrogz
    Mar 2 '11 at 16:15
2
\$\begingroup\$

Windows PowerShell, 67

('NO','YES')[($a=[Convert]::ToString("$input",2))-eq-join$a[64..0]]
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 17 12 bytes (non-competing)

‘NO…Ü‘#EbÂQè

-5 bytes thanks to Adnan.

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Hey nice! I tried to golf it a bit and came to 12 bytes ‘NO…Ü‘#EbÂQè :). \$\endgroup\$
    – Adnan
    Sep 25 '16 at 19:14
  • \$\begingroup\$ Great! I still don't know how to use/make compressed strings. Also, I didn't know the function bin() existed \$\endgroup\$
    – acrolith
    Sep 25 '16 at 19:47
  • 2
    \$\begingroup\$ There is actually a detailed example here, if you are interested :). \$\endgroup\$
    – Adnan
    Sep 25 '16 at 20:05
  • \$\begingroup\$ This answer is non-competing since the question predates the language. \$\endgroup\$
    – Okx
    Feb 2 '17 at 20:08
1
\$\begingroup\$

Python (51)

n=bin(input())[2:]
print'YES'if n==n[::-1]else'NO'
\$\endgroup\$
1
  • \$\begingroup\$ You can ['NO','YES'][n==n[::-1]] \$\endgroup\$
    – Karl Napf
    Nov 3 '16 at 15:35
1
\$\begingroup\$

Perl (73)

No string reverse:

print f(split//,sprintf'%b',shift);
sub f{@_<=1?YES:shift!=pop()?NO:f(@_)}
\$\endgroup\$
1
\$\begingroup\$

Perl (127)

This one constructs all palindromes up to 2^32.

sub f{
    my($x,$l)=@_;
    $l+=2,f(($x<<$_)+1+(1<<$l-1),$l)?return 1:0 for 1..15-$l/2;
    $x-$ARGV[0]?0:1
}
print f(0,1)+f(0,0)+f(1,1)?YES:NO
\$\endgroup\$
1
\$\begingroup\$

Bash, 55 chars

C=`dc<<<$1\ 2op`;[ $C = `rev<<<$C` ]&&echo YES||echo NO
\$\endgroup\$
1
  • \$\begingroup\$ Well, technically that's bash and dc and rev :-) \$\endgroup\$
    – user56228
    Sep 23 '16 at 13:26
1
\$\begingroup\$

J - 33 characters

13 : ';(]-:|.)#:y{''YES'';''NO'''
\$\endgroup\$
1
\$\begingroup\$

J: 24

((-:|.)#:x){2 3$'NO YES'

eg:

   ((-:|.)#:5){2 3$'NO YES'
YES
   ((-:|.)#:12){2 3$'NO YES'
NO
   ((-:|.)#:125){2 3$'NO YES'
NO
   ((-:|.)#:63){2 3$'NO YES'
YES
\$\endgroup\$
1
\$\begingroup\$

Haskell (79)

0?k=n;n?k=div n 2?(n`mod`2+k*2);f x|x==x?0="YES"|True="No";main=interact$f.read
\$\endgroup\$
2
  • \$\begingroup\$ Don't forget: In Haskell, this will work with really big numbers. \$\endgroup\$
    – FUZxxl
    Feb 8 '11 at 21:13
  • 2
    \$\begingroup\$ Ahm, that's actually 79 characters. ;-) \$\endgroup\$ Feb 8 '11 at 22:49
1
\$\begingroup\$

C (77 bytes)

r,t;main(n){for(t=n=atoi(gets(&n));n;r*=2,r|=n%2,n/=2);puts(r-t?"NO":"YES");}

TEST

\$\endgroup\$
1
\$\begingroup\$

Pyth, 18 bytes

%2>"YNEOS"!qJ.BQ_J

Also 18 bytes:

@,"NO""YES"qJ.BQ_J
\$\endgroup\$
1
\$\begingroup\$

PHP, not competing

I wanted to do it without using strings at all.

iterative solution, 78 bytes

for($x=log($n=$argv[1],2);$i<$x&($n>>$i^$n>>$x-$i^1);$i++);echo$i<$x/2?NO:YES;

recursive solution, 113 bytes

function p($n,$x=0){return$n<2?$n:is_pal(($n&(1<<$x=log($n,2)/2)-1)^$n>>$x+!is_int($x));}echo p($argv[1])?YES:NO;

If n is a binary palindrome, the upper half xor the lower half is also a binary palindrome and vice versa.


a port of the excellent C answer from fR0DDY, 58 bytes

for($x=2*$v=$argv[1];$x/=2;$r=$r*2|$x&1);echo$r-$v?NO:YES;

a binary reverse. Columbus´ egg.

\$\endgroup\$
1
\$\begingroup\$

Retina, 80 78 bytes (non-competing)

Byte count assumes ISO 8859-1 encoding.

.+
$*
+`(1+)\1
${1}0
01
1
^((.)*?).??((?<-2>.)*$)
$1¶$3
O$^`.(?=.*¶)

^(.*)¶\1

Try it online

Convert to unary. Convert that to binary. Cut the number in half and remove a middle digit if there is one. Reverse the first half. Match if both halves are equal.

\$\endgroup\$
1
\$\begingroup\$

Jelly, 12 bytes (non-competing)

BṚ⁼Bị“YES“NO

Try it online!

Explanation:

BṚ⁼Bị“YES“NO Main link. Arguments: z.
B            Binary representation of z.
 Ṛ           Reversed.
   B         Binary representation of z.
  ⁼          Check if x is equal to y.
     “YES“NO [['Y', 'E', 'S'], ['N', 'O']]
    ị        xth element of y (1-indexed).

Before printing, Python's str function is mapped through a list, and then the elements are concatenated, so you see YES or NO.

\$\endgroup\$
1
\$\begingroup\$

Arn, 16 bytes

±î«Áýãf©¯tvf–ɉ2

Try it!

Explained

Unpacked: "YES"^(=\|:;b)||"NO. Man that yes/no required output really killed my byte count

    "YES"         String
  ^               Repeated
    (             Begin expression
        \         Fold with...
      =           ...equality
          |:      Bifurcate
              _   Variable initialized to STDIN; implied
            ;b    Binary representation
    )             End expression
||                Boolean OR
  "NO             String, ending quote implied

This works because empty strings are falsey.

\$\endgroup\$
1
\$\begingroup\$

Pyth, 16 bytes

?q_K.BQK"YES""NO

Try it online!

?q_K.BQK"YES""NO
   K.BQ          // Assign binary input to K
?q_K   K         // Evaluate whether K and reversed K are equal
        "YES""NO // Ternary output.
\$\endgroup\$
1
+200
\$\begingroup\$

APL (Dyalog Unicode), 23 bytes (SBCS)

'NO' 'YES'⊃⍨≡∘⌽⍨2⊥⍣¯1⊢⎕

-3 bytes from Bubbler, after fitting the question requirements.

Instead of performing an if-else like below, this program uses APL's representation of true as 1 and false as 0 to select from an array, where 'NO' is in the 0th index and 'YES' is in the first index.

Try it online!

APL (Dyalog Unicode), 26 bytes (SBCS)

{(⌽≡⊢)2(⊥⍣¯1)⍵:'YES'⋄'NO'}

Explanation

{(⌽≡⊢)2(⊥⍣¯1)⍵:'YES'⋄'NO'}
{                        } function wrapper
             ⍵             take the right argument
      2(⊥⍣¯1)              convert to base 2, and split into -1 groups(gets all digits)
 (⌽≡⊢)                     reverse equals right expression?
              :'YES'⋄'NO'} if the above is true, display 'YES', otherwise 'NO'

Try it online!

\$\endgroup\$
7
  • \$\begingroup\$ @petStorm Right, somehow I didn't notice that either. Adding at the end solves the problem. \$\endgroup\$
    – Bubbler
    Aug 28 '20 at 0:24
  • \$\begingroup\$ You can write a full program with test cases on TIO like this. Some golfing gives 24 bytes (which is the same length as tacit). \$\endgroup\$
    – Bubbler
    Aug 28 '20 at 0:32
  • \$\begingroup\$ Oh, sorry about that. I'll fix it soon. Thanks for the help! \$\endgroup\$
    – Razetime
    Aug 28 '20 at 1:58
  • \$\begingroup\$ 23 bytes with (⌽≡⊢) → ≡∘⌽⍨ (because ≡∘⌽⍨x → x≡∘⌽x → x≡⌽x) \$\endgroup\$
    – Bubbler
    Aug 28 '20 at 2:38
  • \$\begingroup\$ A second commutation. Got it. \$\endgroup\$
    – Razetime
    Aug 28 '20 at 2:39
0
\$\begingroup\$

Haxe, 164 bytes

Works only with system platforms (php, neko, cpp, etc.). Takes input through command line arguments.

class T{static function main(){var r:Dynamic=Std.parseInt(Sys.args()[0]);var s=r.toString(2);trace(s==[for(i in-s.length+1...1)s.charAt(-i)].join('')?"YES":"NO");}}
\$\endgroup\$
0
\$\begingroup\$

Matlab, 71 bytes

function paly(n)
v=de2bi(n);
if v==v(numel(v):-1:1)
'YES'
else
'NO'
end
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ Sep 24 '16 at 17:56
0
\$\begingroup\$

Wolfram Language (Mathematica), 46 bytes

If[PalindromeQ@IntegerDigits[#,2],"YES","NO"]&

Try it online!

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 13 bytes

bÂQi'…Üë'€¸}u

Try it online!

bÂQi'…Üë'€¸}u  # full program
   i           # if...
 Â             # implicit input...
b              # in binary...
  Q            # is equal to...
 Â             # implicit input...
b              # in binary...
 Â             # reversed...
    '…Ü        # then push "yes"
       ë       # else...
        '€¸    # push "no"
           }   # exit if statement
            u  # convert to uppercase
               # implicit output
\$\endgroup\$
-2
\$\begingroup\$

Java, 97 85 characters

return Integer.toBinaryString(i).equals(new StringBuffer(s).reverse()+"")?"YES":"NO";
    String s=Integer.toBinaryString(i);
    return s.equals(new StringBuffer(s).reverse()+"")?"YES":"NO";
\$\endgroup\$
1
  • 3
    \$\begingroup\$ The task calls for a full program. \$\endgroup\$
    – Joey
    Mar 2 '11 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.