text:
Binary tree fractal
Today's challenge is to draw a binary tree as beautiful ascii-art like this example:
                               /\
                              /  \
                             /    \
                            /      \
                           /        \
                          /          \
                         /            \
                        /              \
                       /                \
                      /                  \
                     /                    \
                    /                      \
                   /                        \
                  /                          \
                 /                            \
                /                              \
               /\                              /\
              /  \                            /  \
             /    \                          /    \
            /      \                        /      \
           /        \                      /        \
          /          \                    /          \
         /            \                  /            \
        /              \                /              \
       /\              /\              /\              /\
      /  \            /  \            /  \            /  \
     /    \          /    \          /    \          /    \
    /      \        /      \        /      \        /      \
   /\      /\      /\      /\      /\      /\      /\      /\
  /  \    /  \    /  \    /  \    /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

You will be given a positive integer as input. This input is the height of the tree. The above example has a height of six.
You may submit either a full-program or a function, and you are free to use any of our default IO methods. For example, printing the tree, returning a string with newlines, returning a 2d char array, saving the tree to a file, etc. would all be allowed.
Trailing spaces on each line are permitted.
Here are some examples of inputs and their corresponding outputs:
1:
/\

2:
 /\
/\/\

3:
   /\
  /  \
 /\  /\
/\/\/\/\

4:
       /\
      /  \
     /    \
    /      \
   /\      /\
  /  \    /  \
 /\  /\  /\  /\
/\/\/\/\/\/\/\/\

5:
               /\
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /\              /\
      /  \            /  \
     /    \          /    \
    /      \        /      \
   /\      /\      /\      /\
  /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

Unfortunately, the output grows exponentially, so it's hard to show larger examples. Here is a link to the output for 8.
As usual, this is a code-golf challenge, so standard loopholes apply, and try to write the shortest program possible in whatever language you choose.
Happy golfing!

Can there be trailing spaces to make all line the same length?

@xnor Yes, that is fine.

Python 2, 77 bytes
S=s=i=2**input()
while s:print S/s*('/'+' '*(s-i)+'\\').center(s);i-=2;s/=s/i

Prints with trailing spaces, terminating with error.
I took this code from my submission to a challenge I posed on Anarchy Golf, plus a one-byte improvement found by xsot. The hardcoded value of 128 was changed to 2**input().
The idea is that each row of the output is a segment copied one or more times. The half after the input split has one copy of each segment, the quarter after the next split has two copies, and so on, until the last line with many segments of /\.
Each segment had a / and \, with spaces in between, as well as on the outside to pad to the right length. The outer padding is done with center.
The variable s tracks the current with of each segment, and the number of segments is S/s so that the total width is the tree width S. The line number i counts down by 2's, and whenever the value s is half of it, a split occurs, and the segment width halves. This is done via the expression s/=s/i. When i reaches 0, this gives an error that terminates the program.
Since anagolf only allows program submissions, I didn't explore the possibility of a recursive function, which I think is likely shorter.

V, 32 bytes
é\é/ÀñLyPÄlx$X>>îò^llÄlxxbPò
|

Try it online!
Hexdump:
00000000: e95c e92f c0ad f116 4c79 50c4 6c78 2458  .\./....LyP.lx$X
00000010: 3e3e eef2 5e6c 6cc4 6c78 7862 50f2 0a7c  >>..^ll.lxxbP..|

Canvas, 11 bytes
/║╶╷［ｌ＼；∔↔║

Try it here!
Explanation:
/║          push `/\` ("/" palindromized so this is a Canvas object)
  ╶╷[       repeat input-1 times
     l        get the width of the ToS
      \       create a diagonal that long
       ;∔     prepend that to the item below
         ↔    reverse the thing horizontally
          ║   and palindromize it horizontally

Haskell, 140 138 135 bytes
e n=[1..n]>>" "
n!f=(e n++).(++e n)<$>f
f 0=[]
f n=1!f(n-1)++['/':e(2*n-2)++"\\"]
b n|n<2=f 1|t<-b$n-1,m<-2^(n-2)=m!f m++zipWith(++)t t

Try it online! Call with b 5, returns a list of strings.
Pretty print usage:
*Main> putStr . unlines $ b 5
               /\
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /\              /\
      /  \            /  \
     /    \          /    \
    /      \        /      \
   /\      /\      /\      /\
  /  \    /  \    /  \    /  \
 /\  /\  /\  /\  /\  /\  /\  /\
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

(some) Explanation:

e n generates a string of n spaces
n!f pads each string in the list of strings f with n spaces left and right
f n draws a "peak" in a n by 2n rectangle
b n draws the binary tree by concatenating two smaller trees and centers a new peak above them

Edit: -3 bytes thanks to Zgarb!

I think 1!f(n-1) and m!f m should save a couple of bytes.

@Zgarb Thanks for pointing out, those precedence rules sometimes get confusing.

J, 49 43 42 bytes
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-))

This evaluates to a verb that takes a number and returns a 2D character array.
Try it online!
Explanation
I first construct a matrix of the values -1, 0 and 1 by iterating an auxiliary verb, and then replace the numbers by characters.
The auxiliary verb constructs the right half of the next iteration, then mirrors it horizontally to produce the rest.
In the following explanation, , concatenates 2D arrays vertically and 1D arrays horizontally.
' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-))  Input is n.
                          ^:(            )  Iterate this verb
                             <:             n-1 times
                               `(       )   starting from
                                    ,&*-    the array 1 -1 (actually sign(n), sign(-n))
                                 ,:@        shaped into a 1x2 matrix:
                                             Previous iteration is y.
                      #                      Take height of y,
                   i.@                       turn into range
                 =@                          and form array of self-equality.
                                             This results in the identity
                                             matrix with same height as y.
                       ,-                    Concatenate with -y, pad with 0s.
       (    )"1@(        )                   Then do to every row:
        |.,-                                 Concatenate reversal to negation.
' /\'{~                                     Finally index entry-wise into string.

Stax, 20 19 bytes
≡mX░R○k╣∙╒ab^◘⌐╖x▼;

Run and debug it

Charcoal, 12 bytes
ＦＮ«→↗⌈Ｘ²⊖ι‖Ｍ

Try it online! Link is to verbose version of code. Explanation:
 Ｎ              Input as a number
Ｆ «             Loop over implicit range
   →            Move right (because mirroring moves the cursor)
         ι      Current index
        ⊖       Decremented
      Ｘ²        Power of 2
     ⌈          Ceiling
    ↗           Draw diagonal line
          ‖Ｍ    Mirror image

The line lengths are 1, 1, 2, 4, 8 ... 2^(N-2), thus the awkward calculation.

JavaScript (ES6), 105 bytes
f=n=>n<2?"/\\":" "+f(n-1).split`/`[0].replace(/|/g,"$`$'$'/$`$`\\$'$'$` \n")+f(n-1).replace(/.*/g,"$&$&")

Works by building the result up recursively from the base case /\. The bottom half is just the previous case with each line duplicated. The top half was a little trickier; it looks as if you want to take the previous case and only keep the two sides but you also have to worry about padding the strings to double the width, so instead I do some regex magic. By taking the leading spaces from the previous case and splitting at every point, I can consider the spaces before and after that point. At each match the spaces before increase by 1 and the spaces after decrease by 1; this can be used to position the / and \ in the correct places. The newlines and padding are also added here; this takes care of all the padding except a trailing space on each line and a leading space on the first line which I have to add manually. (Leading spaces on subsequent lines come from the matched string).

Batch, 218 bytes
@echo off
set/a"n=1<<%1"
set s=set t=
%s%/\
set l=for /l %%i in (2,1,%n%)do call
%l% %s% %%t%%
%l%:l
:l
echo %t%
set/an-=1,m=n^&n-1
%s%%t: /=/ %
%s%%t:\ = \%
if %m% neq 0 exit/b
%s%%t:/ =/\%
%s%%t: \=/\%

Note: Line 6 ends in a space. Works by moving the branches left and right appropriately each time, except on rows that are 2n from the end, in which case the branches get forked instead.

Haxe, 181 bytes
function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");

Or, with some optional whitespace:
function g(n):String
  return
    (n -= 2) == -1
    ? "/\\"
    : [ for (y in 0...1 << n)
        [ for (x in 0...4 << n)
          x + y + 1 == 2 << n
          ? "/"
          : x - y == 2 << n
            ? "\\"
            : " "
        ].join("")
      ].concat([ for (y in g(n + 1).split("\n"))
        y + y
      ]).join("\n");

I was working for a while on a solution which created an array of space characters of the right size first, then iteratively put the forked paths lower and lower (and more densely at each iteration). It remained 230+ bytes, though. The approach here is pretty much what @Laikoni's Haskell approach is. I couldn't get away with not having :String, because Haxe is not smart enough to identify that the return type will always be a String.
This is a function only, here's a full programme to test it:
class Main {
    public static function main(){
        function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n");
        Sys.println(g(Std.parseInt(Sys.args()[0])));
    }
}

Put the above in Main.hx, compile with haxe -main Main.hx -neko frac.n and test with neko frac.n 4 (replace 4 with the desired order).

PHP, 188 Bytes
Online Version
function f($l,$r=0,$m=1){global$a;for(;$i<$l;$i++)$i<$l/2?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m):f($l/2^0,$r+$l/2,2*$m);}f(2**$argv[1]/2);echo join("\n",$a);

Expanded
function f($l,$r=0,$m=1){
global$a;
for(;$i<$l;$i++)
$i<$l/2
    ?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m)
    :f($l/2^0,$r+$l/2,2*$m);
}
f(2**$argv[1]/2);
echo join("\n",$a);


text:
Draw the XNOR digital timing diagram
Below is a (schematic) Digital timing diagram, for the XNOR logic gate.
    ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
A ──┘ └─┘ └─┘     └─┘ └─┘ └─┘   └──
  ┌───┐ ┌───┐ ┌─┐ ┌─────┐   ┌─┐ ┌─┐
B ┘   └─┘   └─┘ └─┘     └───┘ └─┘ └
    ┌─────┐   ┌─┐   ┌─┐   ┌───┐
X ──┘     └───┘ └───┘ └───┘   └────

Your goal is to reproduce it exactly as depicted.
Rules:

You can either print it or return a multiline string;
Arbitrary number of traling and/or leading newlines are allowed;
Trailing (but not leading !) whitespace is allowed;
If you can not use the extended ASCII box-drawing characters,
you may substitute them for the unicode equivalents (at no byte penalty).

This is code-golf so the shortest answer in bytes wins.
Binary Representation
For your convenience, binary representation of the diagram above is as follows:
INP A=0101011101010110
INP B=1101101011100101
  ___
X=A⊕B=0111001001001100

Sample Output

Sidenote
While working on this question, I've implemented two different bash solutions for it, one is 122 characters/bytes long (as depicted above), and another one is exactly 100 bytes long.
I do not have plans to post them (as I don't normally post answers to my own questions), so that is just for reference.
I also believe that at least some sub-100 byte solutions are possible.

That's an XNOR gate, isn't it...

@Qwerp-Derp Yep, maybe it is :)

Instead of suggesting (0==0)==0 shan't either B or X start and end at 1?

@Roman Czyborra Not sure I understand the idea, could you elaborate on this a bit ?

@zeppelin Look right at the beginning of the pattern - the first couple pixels. A, B and X are all low there. The same is true at the end. Why is this the case? (I believe this is Roman's question).

@isaacg, only A and X are low, B is high, but as it starts with "light up and left" - ┘, it makes it look like it transitions from low. This is a peculiarity of using ASCII art to represent the diagram.
Starting with all 1es, would have probably made it look nicer, but that is too late for this kind of change.

@xnor how'd he get your selfie?

05AB1E, 101 bytes + 5 UTF-8 bytes = 116 Total Bytes = 106 Bytes
(LEGACY 05AB1E VERSION, NO LONGER ON TIO)
•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•6B"102345"" ┌─┐└┘"‡6ävyN" A B X"èì}»

Try it online!
The compression:
•=(Ín§Àoà`œ¯_eè8y1ÜŸ,Ú®:¹$:,õKA–x[Âì0ãXÔfz}y×ì¹Ï½uEÜ5äÀTë@ºQÈ™ñó:ò…Eä•
# Pattern, converted to base-6 in base-6=214.

111023102310222223102310231022231112251425142511111425142514251114221022231022231023102222231110231023151114251114251425111114222514251411102222231110231110231110222311111225111114222514222514222511142222
# Actual base-6 pattern.

1110231023102222231023102310222311
1225142514251111142514251425111422
1022231022231023102222231110231023
1511142511142514251111142225142514
1110222223111023111023111022231111
1225111114222514222514222511142222
#Pattern split into chunks of 34.

   ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
 ──┘ └─┘ └─┘     └─┘ └─┘ └─┘   └──
 ┌───┐ ┌───┐ ┌─┐ ┌─────┐   ┌─┐ ┌─┐
 ┘   └─┘   └─┘ └─┘     └───┘ └─┘ └
   ┌─────┐   ┌─┐   ┌─┐   ┌───┐
 ──┘     └───┘ └───┘ └───┘   └────
# Pattern after replacing 0,1,2,3,4,5 with appropriate blocks.

The conversion:
6B                                   # Convert back to base-6.
  "102345"" ┌─┐└┘"‡                  # Replace numbers with appropriate counterparts.
                   6ä                # Split into 6 equal parts (the rows).
                     vy           }  # For each row (chunk).
                       N" A B X"èì   # Push label at index [i], prepend to line.
                                   » # Print all separated by newlines.

Using the CP-1252 encoding.

You are allowed to count each unicode box-drawing character as just 1 byte, for the purposes of this challenge (see "Rules"),
so your answer is 106 bytes long according to this.
The rationale is that these unicode characters can be replaced with 1 byte characters  e.g. in CP437 or IBM850, but these can be more tricky to display.

I agree with zeppelin. Given the concession given in the rules, this would therefore be 106 bytes.

Alternative method that only works in the new version of 05AB1E using the builtin Åв (I've also updated the ASCII-art generator tip with this): 106 bytes

Bubblegum, 76 bytes
00000000: 92d6 3000 5431 1505 1403 50e8 4e0a aafc  ..0.T1....P.N...
00000010: 9f62 15e6 a3ff 61fa dc05 e06d 8b66 cbc7  .b....a....m.f..
00000020: e6b6 cff8 519a b85a 3eb6 b67d 95c0 0feb  ....Q..Z>..}....
00000030: 35b5 521d 7f7e 68af a916 fa20 d999 564d  5.R..~h.... ..VM
00000040: 1f03 d559 59ed 265c f243 42be            ...YY.&\.CB.

Try it online!
Uses box-drawing characters from the VT100 alternate character set, which TIO can’t demonstrate.  Run in a UNIX terminal for best results.  My terminal converts the ACS to UTF-8 on copy-and-paste, so you can see the effect here.
anders@change-mode:/tmp$ bubblegum xnor.zlib
    ┌─┐ ┌─┐ ┌─────┐ ┌─┐ ┌─┐ ┌───┐
A ──┘ └─┘ └─┘     └─┘ └─┘ └─┘   └──
  ┌───┐ ┌───┐ ┌─┐ ┌─────┐   ┌─┐ ┌─┐
B ┘   └─┘   └─┘ └─┘     └───┘ └─┘ └
    ┌─────┐   ┌─┐   ┌─┐   ┌───┐
X ──┘     └───┘ └───┘ └───┘   └────
▒┼␍␊⎼⎽@␌␤▒┼±␊-└⎺␍␊:/├└⎻$

Well, the challenge didn’t say we need to take the terminal back out of ACS mode before returning to the shell.  Good luck with that.

Ruby, 113 bytes
counting printed symbols as one byte as authorised by the challenge (I was surprised to discover they are actually 3 bytes.)
6.times{|i|s=' A B X'[i]
'D]zunIWkF]nIRukFH'.bytes{|b|s+='   ┌─┐───┘ └'[(b*2>>i/2*2&6)-i%2*6,2]}
s[1]=' '
puts s}

6 lines of output lends itself to an encoding of 6 bits per each character of the magic string. But the magic string characters actually encode for each transition thus:
least significant bit 0 New value for A
                      1 Current value for A
                      2 New value for B
                      3 Current value for B
                      4 New value for X
                      5 Current value for X
most significant bit  6 Always 1 (to remain in printable range)

This is decoded to find the 2 characters that must be printed for each transition (the first of which is either space or a horizontal line.)
The 8-character strings for the upper and lower rows overlap: The last two characters for the upper row 11 are two horizontal lines, which matches with what is needed for the first two characters of the lower row 00. The 8 characters for the lower row wrap around: they are last 6 and first 2 characters of the symbol string.
Ungolfed code
6.times{|i|s=' A B X'[i]               #iterate through 6 lines of output. Set s to the 1st character.
  'D]zunIWkF]nIRukFH'.bytes{|b|        #for each byte in the magic string
     s+='   ┌─┐───┘ └'[(b*2>>i/2*2&6)- #add 2 bytes to s, index 0,2,4, or 6 of the symbol string depending on relevant 2 bits of the magic string.
     i%2*6,2]                          #if the second (odd) row of a particular graph, modify index to -6,-4,-2, or 0
  }                                    #(ruby indices wrap around. mystring[-1] is the last character of the string.)
  s[1]=' '                             #replace intitial ─ of the curve with space to be consistent with question
  puts s                               #output line
}

This is actually 129 bytes, 113 characters.

@carusocomputing I see you have made the same comment on most of the answers here. Please refer to the first line of my anser and to rule 4 of the OP: If you can not use the extended ASCII box-drawing characters, you may substitute them for the unicode equivalents (at no byte penalty) We have all scored our answers according to the rules.

PowerShell, 255 characters, 265 bytes (UTF-8)
$a='    012 012 0111112 012 012 01112
A 113 413 413     413 413 413   411
  01112 01112 012 0111112   012 012
B 3   413   413 413     41113 413 4
    0111112   012   012   01112
X 113     41113 41113 41113   41111'
0..4|%{$a=$a-replace$_,('┌─┐┘└'[$_])};$a

This works on my computer, but doesn't seem to parse the bytes correctly on TIO...

This sets $a to be a multi-line string filled with numbers and spaces, then loops 0..4|%{...}. Each iteration, we -replace the appropriate digit $_ with the appropriate character '┌─┐┘└'[$_] and store it back into $a. Then, we just leave $a on the pipeline and output is implicit.

You are allowed to count the unicode characters as single bytes, according to the challenge

JavaScript (ES6), 163 158 154 bytes
NB: counting UTF-8 characters as bytes, as authorized by the challenge.
_=>[..." A B X"].map((c,i)=>c+" "+[...Array(33)].map((_,j)=>j%2?" ─"[p^i&1]:" ┐┌─└┘ "[p+(p=[27370,42843,12878][i>>1]>>j/2&1)*2+i%2*3]).join``,p=0).join`
`

Demo

let f =

_=>[..." A B X"].map((c,i)=>c+" "+[...Array(33)].map((_,j)=>j%2?" ─"[p^i&1]:" ┐┌─└┘ "[p+(p=[27370,42843,12878][i>>1]>>j/2&1)*2+i%2*3]).join``,p=0).join`
`

console.log(f())

Saved 4 bytes thanks to Neil

j%2?" ─"[p^i&1]:" ┐┌─└┘ "[p+(p=[27370,42843,12878][i>>1]>>j/2&1)*2+i%2*3] saves 3 bytes.

Oh, and change 17 to 33 too.

Once again, 152 characters, 164 bytes.

C, 213 205 bytes
For a change, the C program size, on this challenge, isn't completely ridiculous compared to other languages.
#define X(a) u[i]=C[a],l[i++]=C[(a)+4]
p(n,c){char u[34],l[34],*C=" ┐┌──└┘ ",i=0;while(i<34)X(n&3),n>>=1,X((n&1)*3);printf("  %.33s\n%c %.33s\n",u,c,l);}main(){p(0xD5D4,'A');p(0x14EB6,'B');p(0x649C,'X');}

Ungolfed, define expanded, and commented:
p(n,c){
    // u is the upper line of the graph, l the lower line
    char u[34],l[34],*C=" ┐┌──└┘ ",i=0;
    while(i<34)
        u[i]=C[n&3],            // using the two LSBs to set the transition char depending on the current and next state
        l[i++]=C[(n&3)+4],      // do for both upper and lower lines
        n>>=1,                  // shift bits right to go to next state
        u[i]=C[(n&1)*3],        // using only the LSB to set the "steady" char depending on current state only
        l[i++]=C[((n&1)*3)+4];  // do for both upper and lower lines
    printf("  %.33s\n%c %.33s\n",u,c,l);
}
main() {
    // Call p for each graph
    // Constants are chosen so the display is consistent with the request.
    // Each bit represents a state, but the order is reversed
    // (leftmost is put on lowest significant bit, after a 0)
    p(0xD5D4,'A');p(0x14EB6,'B');p(0x649C,'X');
}

Note: the C string must not contain unicode characters. All displayable characters must be plain old 8-bit chars (but they may be chosen in the extended range). So basically, the validity of the output depends on your code page.

tcl, 221 chars, 299 bytes
lmap {b _ n u A V} {"   " ┌─────┐ ┌───┐ └───┘ ┌─┐ └─┘} {puts "[set S \ $b][set m $A\ $A] $_ $m $n
A ──┘ [set w $V\ $V][set s \ $S]$w $V$b└──
  $n $n $A $_$b$m
B ┘$b$V$b$w$s$u $V └
$S$_$b$A$b$A$b$n
X ──┘$s$u $u $u$b└────"}

can be run on: http://rextester.com/live/VVQU99270

228 characters, however it is 306 bytes.

@carusocomputing: What online tool do you use to count bytes instead of chars? Tks in advance.

https://mothereff.in/byte-counter

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
12 hour to 24 hour time converter
Amazingly, this simple task doesn't seem to exist already, so...
Your task is to write a program that takes as input a 12 hour time,  and converts it into "military time", or 24-hour time format.
Input will be in the form:
HH:MM am/pm

Although slight variations are allowed:

The space separating the am/pm from the rest of the time is optional.
The last part can either be "am"/"pm",  or "a"/"p".
Any capitalization is fine.

Output will be the inputted time, transformed into 24-hour format. It can be a number, or a string.
For both the input and output:

0s in the first place are optional. 0s in the last 3 places are mandatory.
the delimiter separating hours and minutes can be a ":", " " (a space), or nothing.

Other notes:

Midnight can be expressed either as 0000, or 2400.
Midnight will be considered "am", while noon will be considered "pm".

Your program can be a function, or a full program, and should either return the result, or output it to the stdout. Trailing whitespace is ok.
Examples (you aren't required to support every format):
12:00am -> 0000
1200 pm -> 1200
1234Am  -> 00:34
134a    -> 134
01:34PM -> 13 34
1234pm  -> 1234

This is code golf, so the smallest number of bytes wins. Since this is so trivial to solve using a built-in, it would be nice to see some code that manually solves this (but use of built-ins are fine).
Just to clarify, you aren't required to support every possible format. Supporting only a single input and a single output format (of your choice) is fine. I would however like to limit the format as outlined above (which is already quite free). {1134,'pm'}, for example, would be unacceptable.

What formats are we required to support? Just one?

@redstarcoder Yes. Any format that conforms to the requirements above is ok, but as noted above the example cases, you aren't required to support every format. A single format of input and a single format of output are fine.

are our formats allowed to require leading zeroes? For example, 01:54pm would work, but 1:54pm wouldn't?

Yes. You can pick the required input format.

Are we allowed to include seconds in our input and output?

@12Me21 No, sorry. The output should be exactly as outlined above. Maybe if this was asked write after I posted it, but this far down the road, I don't want to start making exceptions to allowed output.

V, 21 17 bytes
Thanks @DJMcMayhem for 4 bytes!
í12:/0:
çp/12
$x

Try it online!
This takes the format HH:MMx where x is either a or p, and returns it in the format HH:MM
Hexdump:
00000000: ed31 323a 2f30 3a0a e770 2f31 3201 2478  .12:/0:..p/12.$x
00000010: 0ae7 612f 2478                           ..a/$x

Explanation:
í12:/0:   | find and replace 12: with 0: (to avoid replacing HH:12)
ç         | on every line
 p/       | that contains a p
   12^A   | increment 12 times (the first number, hours)
$x        | delete the character at the end of the line

The input will always be in [1-12] right? In that case, I think you could do ó^12/0 instead of cw^R=^R"%12

Also, you could use the "global command" to apply a command to lines matching a regex, which is shorter than breaking a macro. çp/12^A which is equivalent to :g/p/norm 12<C-a> in vim

I accepted this because it was the lowest scoring answer that made it clear it wasn't using a built in (even though I didn't forbid using them). If anyone has a problem with this choice, I can change my answer to be fair. I think this answer is the most deserving though.

MATL, 4 bytes
15XO

Try it online!
Explanation
Built-in function: date string conversion with automatic detection of input format and with output format 15, which corresponds to 'HH:MM'. This is equivalent to @StewieGriffin's Octave answer.

Octave, 21 17 bytes
Saved 4 bytes thanks to Luis Mendo. I could specify format number 15 instead of 'HHMM'.
@(c)datestr(c,15)

Explanation:
This is an anonymous function taking a string c as input on the format: '11:34 AM'. datestr recognizes the format automatically as one of the standard date formats, and outputs it in the specified format number 15, which is HH:MM.
Since the specified output format doesn't have AM or PM Octave automatically converts it to what you refer to as Military time.
Try it online.

A version not using datestr using 35 bytes
@(c)[c(1:4)+[1,2,0,0]*(c(5)>97),'']

Explanation:
Takes an input string c on the format 1134am.
@(c)                              % Anonymous function
[c(1:4)                           % First 4 elements of the string
       +[1,2,0,0]                 % Add 1 and 2 to the first to the ASCII-value of the
                                    first two characters
                 *)c(5)>97)       % if the fifth element is larger than 97
                                    (the ASCII code for `a`).
                            ,'']  % Implicitly convert to string

Or, a different approach for 37 bytes:
@(c)[c(1:4)+('1200'-48)*(c(5)>97),'']

PowerShell, 23 20 19 bytes
date "$args"-f HHmm

Try it online!
(If you're on Windows, you can omit the get-, to get down to 19 bytes. On TIO, it apparently requires the full Get-Date name.)
Takes input as a string $args[0], uses that as the input to the Get-Date cmdlet, which parses it into a .NET datetime object. That's passed with the -format parameter of HHmm to convert it to military time (the capital HH specifies 24-hour time). Output is implicit.
The parsing engine is pretty robust, so additional inputs like 12am or 12:00am are allowed as well. Play around with the input on TIO and see what else works.
(Saved 3 bytes thanks to @admalledd ... saved another byte thanks to @briantist)

Should be able to remove the space between $args[0] and -f, as well as remove the single quotes around the format str: date $args[0]-f HHmm. At least this works on my powershell...

@admalledd For crying out loud, I always forget those quotes. Seriously, I think every single time I've used Get-Date with -f, someone has reminded me that you don't need the quotes. And good call with removing the space, too, since the parser treats the ] as the end of a token. Thanks!

Python 2, 44 bytes
lambda s:`int(s[:2])%12+12*("p"in s)`+s[3:5]

Input format: 01:23am, optional m and spaces after minutes
Output format: 123

Pyth, 21 20 bytes
Aczd++*12}\pH%sG12PH

Takes input of the form 01 23a as "01:23 am". Initial 0 is optional.
Output is of the form 123, with the initial 0 omitted.
In pseudocode:
                         z = input()
A                        G, H =
 czd                         z.split(" ")       # splits into the form ["1","23p"]
                         (
     +*12}\pH            12*('p' in H) +        # add 12 if 'p' is in the string
             %sG12         int(G) % 12
    +             PH     ) + H[:-1]             # prepend hour to minutes, with a/p removed

Try it online!

PHP, 35 32 bytes
input format: case insensitive, requires colon and the m, output format hhmm.   uses built-ins:
<?=date(Hi,strtotime($argv[1]));

takes input from first command line argument.
PHP, 45 bytes, no built-ins
input format (h)h:mm a(m) lowercase, output format (h)hmm.
<?=($s=$argv[1])%12+12*($s[6]>a).$s[3].$s[4];

Why the downvote?

I'm just speculating but maybe it's because you used PHP and the downvoter does not like PHP? :p

Java 7, 138 106 105 104 bytes
String a(String a){return new java.text.SimpleDateFormat("Hmm").format(new java.util.Date("Ja1,0,"+a));}

Try it online!
Input is colon delimited and has a space between the time and the am/pm. Output is not colon delimited.
-1 byte thanks to Kevin Cruijssen

Bout as short as it gets for Java, 20% of the code being package qualifiers.

The rules state this "For both the input and output: - 0s in the first place are optional. 0s in the last 3 places are mandatory.", which means you can change HHmm to Hmm.

@KevinCruijssen nice catch!

GNU Coreutils (18 16 bytes)
From a shell script:
Does not accept whitespace in the input
At which point, may as well use $1 and ignore additional args.
date -d$1 +%H%M

⇒ echo 'date -d$1 +%H%M' > time24
⇒ sh time24 1:45pm
1345
⇒ sh time24 1:45 pm
0145 # Wrong answer, “pm” ignored because of space

Original
To allow whitespace in the input,
date -d"$@" +%H%M

JavaScript (ES6), 40 bytes
a=>(new Date('1/1/1/'+a)+a).slice(16,21)

Input should be formatted like: 12:32 am

C#, 46 bytes
s=>System.DateTime.Parse(s).ToString("HH:mm");

Strings are taken in input like 12:00 AM
Doing the same thing but substringing on the output from the default call to ToString (Assuming a culture of en-GB) is 3 bytes longer for 49 bytes:
s=>(System.DateTime.Parse(s)+"").Substring(11,5);

date, 0 + 8 = 8 bytes
On the subject of using the right tool for the job…
Takes input as a command line argument. Run with +%H%M -d (8 byte penalty). There's no actual program here; the entire work is done by the command-line arguments. (This is a pretty good demonstration of why there's a penalty for command-line arguments!)
Example:
$ date +%H%M -d "12:05 am"
0005

Perl, 45 28 37 bytes
28 37 bytes
(c/o @Dada)
(36 bytes code, 1 byte for compiler -p switch)
Accepts 0145pm type formats, with am/pm or a/p. Leading zeroes on inputs required.
s/(..)(.)$//;$_=$_%12+12*(p eq$2).$1

Test:
⇒ echo 0145pm | perl -p time24
1345
⇒ echo 0245pm | perl -p time24
1445
⇒ echo 1245pm | perl -p time24
1245
⇒ echo 1245am | perl -p time24
045

My original answer
(also gently revised)
(39 bytes code, 1 byte for compiler -p switch.)
Accepts only the form like 0145p or 0145a, and no other, and requires perl -p mode to work.
s/(..)(..)([ap])/$1%12+12*($3eq"p").$2/e

test:
⇒ echo 0145p | perl -p time24
1345
⇒ echo 1222a | perl -p time24
022
⇒ echo 1234p | perl -p time24
1234

Welcome on PPCG. Nice first answer. You can use switches, but they count in your bytecount (as explained here). In your case, that would be +1 byte (because only -p is needed) if you change the single quotes for double quotes.

Thanks. Couldn't find that FAQ, wonder if Stack Exchange team could pin it on the answer page or something?

OK, I've been Perling since the 4 series and that makes my head hurt, you should take the credit and post yourself with that one. ☺

I think that should cover it now?

I made a mistake, this solution won't work when the minutes are between 0 and 9. This code works then: s/(..)(.)$//;$_=$_%12+12*(p eq$2).$1 (37 bytes). And by the way, your first solution can be golfed down a little bit: s/(..)(..)([ap])/$1%12+12*($3eq"p").$2/e (40 bytes)

Japt, 14 bytes
Ð"1/"+U s sG21

Try it online!
This only works on Chrome. Here's a version that works in all browsers:
Ð"1/"³+U s sG21

Thanks again to ETHproductions for the help!

C, 87 72 bytes
Saved 15 bytes thanks to @Johan du Toit
Call f() with a mutable string as an argument, the input is the output.
The format is HH:MMa/p, where a/p is either lowercase a or lowercase p. No space between the time and the meridian specifier is allowed.
i;f(char*p){i=atoi(p)%12+(p[5]^97?12:0);*p=i/10+48;p[1]=i%10+48;p[5]=0;}

Try it on ideone.

you can save a couple of bytes by using the following: i;f(char*p){i=atoi(p)%12+(p[5]^97?12:0);*p=i/10+48;p[1]=i%10+48;p[5]=0;}

Suggest (p[5]!=97)*12; instead of (p[5]^97?12:0);

C (clang), 94 bytes
h,m;f(){char a,b;scanf("%d:%d%c%c",&h,&m,&a,&b);printf("%02d%02d",a=='a'?(h%12):(12+h%12),m);}

Try it online!
I'm here to learn, so any tips on how i can optimize the code are welcome.
@ Johan du Toit Thanks, for saving a few bytes!

You do not have to test if b == 'm' and you can make it much shorter by using inline if statements: printf("%02d:%02d", (a=='p' ? 12 : 0) + (h %12), m);

@JohanduToit What i input is 6:00pc ? :)

That will cause irreparable harm to the space-time continuum.

75 bytes

tcl, 45 47
Now using a built-in:
puts [clock f [clock sc $s -f %I:%M%p] -f %R]

Testable on http://rextester.com/TSRXI8802 where there is a script that runs it from 0100am to 1259pm

Commodore 64 BASIC, 301 bytes before running, 321 bytes used once run
0 A$="12:34AM":A=VAL(LEFT$(A$,2)+MID$(A$,4,2)):ON-(RIGHT$(A$,2)="AM")+1GOSUB1,2:TI$=A$:PRINTTI$:END
1 ON-(A=>1200ANDA<=1259)GOTO3:A=A+1200:GOTO3
2 ON-(A=>1200ANDA<=1259)GOTO4:ON-(A<=959)GOTO7:RETURN
3 A$=RIGHT$(STR$(A)+"00",6):RETURN
4 A=A-1200:IFA=0THENA$="000000":RETURN
5 IFA<10THENA$="000"+RIGHT$(STR$(A),1)+"00":RETURN
6 A$="00"+RIGHT$(STR$(A),2)+"00":RETURN
7 A$="0"+RIGHT$(STR$(A),3)+"00":RETURN

In order to enter this on a real Commodore 64, you will need to use BASIC keyword abbreviations, such as LE[shift]F for LEFT$, M[shift]I for MID$ etc... or you could try CBM PRG STUDIO.
The TI$ variable in Commodore BASIC presents the time in 24 hour clock format as HHMMSS when printed. Taking the space out after the line number does not save any memory as Commodore BASIC adds in the space automatically anyway when you list the program after entering it.
When converting a number to a string with STR$, Commodore BASIC will add in the space (so if you PRINT A you will see a space before the number is shown), I've removed the opening space on the number to string conversion with the RIGHT$ command. You could save a few bytes by amending line zero to:
0 A=VAL(LEFT$(A$,2)+MID$(A$,4,2)):ON-(RIGHT$(A$,2)="AM")+1GOSUB1,2:TI$=A$:PRINTTI$:END

so you will need to declare your time to convert before running the program, as follows:
A$="01:22AM":GOTO 0

At any moment thereafter, you can see the current time with:
? TI$

Playing code golf on 8-bit machines is really interesting as it shows how much is done for a modern-days programmer without even needing to think about it.

SmileBASIC, 67 bytes
INPUT T$P=POP(T$)>"a
TMREAD"00:"+T$OUT,H,M?H MOD 12+12*P,T$[3];T$[4]

Input: HH:MMa/p
Output: HH  MM

REXX, 33 bytes
arg h':'m a
say h+((a=pm)*12)':'m

Use:
12:34 pm -> 24:34
1:34 pm -> 13:34
1:34 am -> 1:34
0:34 AM -> 0:34

This could be shortened by a few bytes if a colon as delimiter was not used.

Colon delimiter is optional.

Yes, but it doesn't look good.

Given this is a code-golfing challenge, if you have the option of a longer program with pretty output, or a shorter program with uglier output, choose the latter. No one will judge you.

Java, 171 bytes
enum t{;public static void main(String[] a){a=a[0].split("[: ]");System.out.format("%02d%02d",(Long.parseLong(a[0])+(a[2].charAt(0)=='p'?12:0))%24,Long.parseLong(a[1]));}}

Input format is HH:MM a/p and output format is HHMM.
Abusing the fact that main function has an array of strings to split the input into 3 sections: hour, minute and a/p indicator.
Example input and output:
Input: 01:02 a
Output: 0102

Input: 01:02 p
Output: 13:02

Input: 12:22 p
Output: 0022

Ungolfed version:
enum t {
    ;

    public static void main(String[] a) {
        a = a[0].split("[: ]");
        System.out.format("%02d%02d", (Long.parseLong(a[0]) + (a[2].charAt(0) == 'p' ? 12 : 0)) % 24, Long.parseLong(a[1]));
    }
}

I hadn't seen enum used to hold the main. Nice :)

You can omit a space in the main method signature: public static void main(String[]a){...

R, 68 bytes
x=substr(strptime(scan(,""),"%I:%M %p"),12,16);`if`(x=="","00:00",x)

Reads input from stdin and it's assumed to be in one of the following formats:

12:00 AM
12:00 am
12:00AM
12:00am

and output is on the format: [1] "00:00"
In most instances strptime() output is on the format: "2017-01-06 12:00:00 CET" where the date is the local date. As such we need to use substr() to only return the time, however, if the input is midnight (e.g. 12:00am) the output is only "2017-01-06 CET" which is the reason for the if thing at the end (there must be some more clever workaround).

I really wanted to find a shorter way with lubridate, but the name of the package is too long (among other problems).

tcl, 88 102 107 110
Naïve attempt:
puts [format %03d [expr {[regsub p $s "" n]?([scan $n %d]+1200)%2400:[regsub a $s ""]}]]

testable on http://rextester.com/live/XUKJU62994 where there is a script that runs it from 0100a to 1259p

C, 159 152 bytes
#define C c[0]
main(i,c)char**c;{scanf("%s",C);i=atoi(C);if(C[5]-97){i+=i-12?12:0;sprintf(C,"%d",i);}else if(i==12)C[0]=C[1]=48;C[2]=58;C[5]=0;puts(C);}

Input format: 07:30am

Pyke, 15 bytes
4<bwӐi%\pQ{i*+

Try it here!

Mathematica, 33 bytes
#~DateString~{"Hour24","Minute"}&

Anonymous function. Takes a string as input and returns a string as output. Works with most formats, including hh:mm AM/PM.

tcl, 66 67 68
scan $s %d%c t c;puts [format %03d [expr $c>97?($t+1200)%2400:$t]]

in http://rextester.com/live/VDSG70132 there is a script that runs it from 0100a to 1259p

JavaScript, 67 bytes
f=s=>!~s.indexOf`pm`?s.slice(0,5):((+s.slice(0,2)+12)+s.slice(2,5))

Input is like in the example

Does not work for 12:00 am or 12:00 pm

Common Lisp (151122 bytes)
OK, CL isn't meant to be “terse” but I'm just surprised that it isn't the most verbose for this one.
Here's the 122 byte version, which requires fixed-position input. 0145pm or 145p are acceptable (with the leading space in the first character-position).
(defun a(x)(let((h(parse-integer(subseq x 0 2)))(m(subseq x 2 4)))(format nil "~a~a" (+(mod h 12)(if(find #\p x)12 0))m)))

PPRINT:
(DEFUN A (X)
  (LET ((H (PARSE-INTEGER (SUBSEQ X 0 2)))
        (M (SUBSEQ X 2 4)))
    (FORMAT NIL
            "~a~a"
            (+ (MOD H 12) (IF (FIND #\p X) 12 0))
            M)))

Nicer but bigger
Using only the Common-Lisp package. Accepts (only) input in the form of integer hours (with or without leading 0), literal :, two-digit minutes, and optional trailing am or pm (in lower-case only). Permits whitespace around the time and around the AM/PM, but not directly after the :.
(defun a(x)(let*((c(position #\: x))(h(parse-integer(subseq x 0 c)))(m(subseq x(1+ c)(+ 3 c))))(format nil "~a~a" (+(mod h 12)(if(find #\p x)12 0))m)))

Test:
GOLF> (a "  1:45 am ")
"1:45"
GOLF> (a "  1:45 pm ")
"13:45"
GOLF> (a " 12:45 am ")
"0:45"
GOLF> (a "12:45p")
"12:45"

pprint the function definition:
(DEFUN A (X)
  (LET* ((C (POSITION #\: X))
         (H (PARSE-INTEGER (SUBSEQ X 0 C)))
         (M (SUBSEQ X (1+ C) (+ 3 C))))
    (FORMAT NIL "~a~a"
            (+ (MOD H 12)
               (IF (FIND #\p X)
                   12
                   0))
            M)))

De-obfuscated:
(defun 12->24-hour (timestring)
  "Given a  TIMESTRING with  hours:minutes and a  trailing “am”  or “pm”
   \(lowercase-only), return the 24-hour time without a delimiter as
   a  string \(eg,  \"1:45am\" →  \"0145\"). Spaces  surrounding the
   time or  meridian markers are ignored  \(eg, \" 02:22 pm  \") but
   other junk in the string may cause incorrect behavior."
  (let ((colon (position #\: timestring)))
    (let ((hours (parse-integer (subseq timestring 0 colon)))
          (minutes (subseq timestring (+ 1 colon) (+ 3 colon))))
      (format nil "~a~a"
              (+ (mod hours 12) (if (find #\p timestring) 12 0))
              minutes))))

Retina, 61 60 bytes
^12(.*)a
00$1
^(12.*)p
$1
a

(\d\d)(.*)p
$1$*x12$*x$2
x+
$.&

Input is given without a separating colon, mandatory leading 0, and using only a or p instead of am or pm, eg 0134a is 01:34 am. Outputs in straight military time using 0000 as midnight. (I could save some bytes if I'm allowed to convert, for example, 12:30 am into 2430, but I doubt that's acceptable).
Try it online!
Explanation
The initial two cases deal with the "12" hours, since am/pm is reversed for 12:
^12(.*)a
00$1

If the time is between midnight (12 am) and 1 am, change it to 00 instead of 12, and remove the a.
^(12.*)p
$1

If the time is between noon (12 pm) and 1pm, remove the p to simply get the 24 hour time.
For any other hour:
a

If the time is am, simply remove the a to get the 24 hour time.
(\d\d)(.*)p
$1$*x12$*x$2
x+
$.&

If the time is pm, remove the p. Convert the hour component to unary, add 12, and convert back to decimal. Leave the minutes unchanged.

Batch, 40 bytes
@set/aa=0,p=12,h=%1%%12+%3
@echo %h% %2

Takes input as three arguments. Assumes second argument has leading zero where necessary, third argument is either a or p. Works by treating the third argument as an indirect variable name therefore adding it on to the number of hours; the number of minutes is unaffected so is just output directly. If mixing different formats is OK then the last space can be deleted to save a byte.
(Rather annoyingly, this question didn't appear on the questions page when I originally loaded it, and I only stumbled across it because I was searching for another question.)

Haskell, 61 characters
Short version:
c[a,b,c,d,e]=(mod(read[a,b]::Int)12+f e,[c,d])
f 'a'=0
f _=12

Input format: HHMM(a/p) where (a/p) is either 'a' or 'p' without parenthesis.
Output format: (hs, MM) – a tuple containing the hours as an integer and MM still as string.
Example:
> c "1200p"
(12,"00")
> c "1200a"
(0,"00")

Longer version (with more useful names and one substitution hs):
conv [h0,h1,m0,m1,ap] = (mod hs 12 + offset ap, [m0,m1])
    where hs = read [h0,h1] :: Int

offset 'a'=  0
offset  _ = 12

Groovy, 49 50 bytes
+1 byte because of invalid output format :(
{t=it.split();(t[0]as int)+(t[2]=="pm"?12:0)+t[1]}

Input is given in format HH MM am or HH MM pm. Output is in format HHMM.
Quick explaination:
it.split() splits the input in an array [hour,  minute, am/pm ] Then it returns the hours concatenated with the minutes, but adds 12 to the hours before returning if the last item of the array is "pm"
Previous solution
 {t=it.split();t[2]=="pm"?(t[0]as int)+12+t[1]:it}

What about "12 00 pm"?

Retina, 46 bytes
.*p
12$0
\D

..(?=..)
$*!
!+
$.&
^12
00
^24
12

Try it online!
Input must supply at minimum 2 digits each for HH & MM and a "p" if applicable. Output only returns a leading 0 for the 12 AM hour (I'm unclear if the note on midnight should be interpreted literally, but if not, that would shave off 1 byte). Works on the example cases, provided you prepend 134a with a 0.
Non-digit characters (besides p) are stripped. Lines lacking a "p/pm" are treated as AM. PM times are shifted up by 12 hours, and 12/24 are simply swapped at the end.

T-SQL, 48 bytes
CREATE PROC t @ DATETIME AS PRINT FORMAT(@,'Hm')

Must be used in SQL Server 2012+. The input is converted to '1900-01-01 HH:mm:ss.sss' and the FORMAT function gets the hour and minute part.
Usage:
EXECUTE t @ = '10:45pm'

AWK, 25 18 bytes
/p/{$1=1200+$1%1200}$0=$1

Try it online!
Input is hhmm am/pm, i.e. the time as a 3 or 4 digit number with whitespace separating the am/pm designator.
Correction applied to account for 12 pm times. Thanks @cnamejj for pointing out issue

I think /p/{$1+=1200}$0=$1%2400 is needed to avoid mapping times like 1234p to 2434.

I see I made the same mistake some others did. However, your solution, @cnamejj , doesn't quite fix the problem. 1234p would become 0034 which is still incorrect. But I believe I see an answer.

Tcl, 76 bytes
if [scan $s %dp%n n -]>1 {set n [expr ($n+1200)%2400]};puts [format %03d $n]

Try it online!

Acc!!, 101 97 bytes
(N*10+N)%12*60+N*10+N-528+N/98*720
Write _/600+48
Write _/60%10+48
Write _%60/10+48
Write _%10+48

Expects input in the form 0123a (all digits mandatory, no separators, lowercase am/pm indicator). Gives output like 0123.
Try it online!
Explanation
Acc!! reads one character code at a time using the N special value. With a sufficiently strict input format, we can read five characters and do a little math to compute the number of minutes since midnight, and from there it's easy to print out the 24-hour time.
Deobfuscated, the first line is
((N-48)*10 + N-48)%12*60 + (N-48)*10 + N-48 + N/98*720

The first character is the tens digit of the hour, and the second character is the ones digit of the hour. We convert both from character codes to the associated digits (N-48) and combine them into a single number (...*10 + ...).
If the hour is 12, we want it to become 0; otherwise, it should stay the same. This is accomplished by a mod 12 operation (%12). (Note: in the golfed code, the %12 also takes care of the -48s here.)
Multiply by 60 in preparation to add the minutes (*60).
Process the next two characters as minutes digits, in the same way as the hours digits ((N-48)*10 + N-48).
Now we want to add 12 to the hour if the next character is p (ASCII 112), or add nothing if it's a (ASCII 97).

We can distinguish the two by int-dividing by 98: N/98 is 0 if N is 97 and 1 if N is 112.
Adding 12 hours is the same as adding 720 minutes: + ...*720

This value is stored in the accumulator, _.
Now for our output, we need:

Tens digit of the hour
Ones digit of the hour
Tens digit of the minute
Ones digit of the minute

The hour is _/60, and the minute is _%60. The tens digit of a number (less than 100) is .../10, and the ones digit is ...%10. Combining a few operations where possible gives the four expressions in the code (remembering that we need +48 to convert digits back to corresponding character codes).

05AB1E, 17 bytes
Çт÷`Ž4µ©*Iþ®%4°O¦

Input-format as HHmmx, where x is a/p; output format as HHmm.
Try it online or verify all test cases.
Explanation:
Ç            # Convert the (implicit) input-string to a list of unicode values
 т÷          # Integer-divide each by 100 (0 for "a" and every digit; 1 for "p")
   `         # Pop and dump all these integers to the stack
    Ž4µ      # Push compressed integer 1200
       ©     # Store it in variable `®` (without popping)
        *    # Multiply it to the top dumped value (the 0/1 for "a"/"p")
Iþ           # Push the input-string again, and only leave its digits
  ®%         # Modulo it by the 1200 from variable `®`
4°           # Push 10^4: 10000
         O   # Take the sum of all values on the stack
          ¦  # Remove the leading "1"
             # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ž4µ is 1200.

Clojure, 143 108 96 bytes
+54 bytes to fix a "noon/midnight bug" where times within the hour after noon/midnight would return wrong values.
-35 bytes by getting ideas from other answers. If the hour is == 12, I make it 0. This reduces the number of cases that need to be dealt with.
-12 bytes thanks to BRFennPocock.
I'm not sure if I'm allowed to compete. I can remove this or mark it as non-competing if necessary. It's not like I'm winning though :)
V3
#(let[[h m[i]](clojure.string/split % #" ")](str(+(if(= i\p)12 0)(mod(Integer/parseInt h)12))m))

Ungolfed:
(defn to-24h [time-str]
  ; Split the string on spaces, then deconstruct out the hour,
  ; minute, and whether it's am or pm
  (let [[hours minutes [ampm]] (clojure.string/split time-str #" ")
        pm? (= ampm \p)
        h (mod (Integer/parseInt hours) 12)]
    (str (+ (if pm? 12 0) h)
         minutes)))

V2
#(let[[h m[i]](clojure.string/split % #" ")h(Integer/parseInt h)h(if(= h 12)0 h)](str(if(= i\p)(+ h 12)h)m))

Ungolfed:
(defn to-24h [time-str]
  ; Split the string on spaces, then deconstruct out the hour,
  ; minute, and whether it's am or pm
  (let [[hours minutes [ampm]] (clojure.string/split time-str #" ")
        pm? (= ampm \p)
        h (Integer/parseInt hours)
        h (if (= h 12) 0 h)] ; 0-out the hours if they're equal to 12 to minimize cases
    (str (if pm?
           (+ h 12)
           h)
         minutes)))

V1
#(let[[h m[i]](clojure.string/split % #" ")p(= i\p)h(Integer/parseInt h)t(= h 12)](str(cond(and(not t)p)(+ h 12)(and t (not p))(- h 12):e h)m))

The Java-interop and library reference are killer, but I think they're probably the best options here. Thank God for restructuring though. Easiest parse ever.
Takes input in the format 12 34 am, and outputs as 034. Drops 0s in the first place.
Ungolfed:
(defn to-24h [time-str]
  ; Split the string on spaces, then deconstruct out the hour,
  ; minute, and whether it's am or pm
  (let [[hours minutes [ampm]] (clojure.string/split time-str #" ")
        pm? (= ampm \p)
        h (Integer/parseInt hours)
        twelve? (= h 12)]
    ; Dispatching to figure out how much needs to be added/subtracted.
    (str (cond (and (not twelve?) pm?) (+ h 12)
               (and twelve? (not pm?)) (- h 12)
               :e h)
         minutes)))

With Built-ins, 83 bytes
(fn[s](let[p #(java.text.SimpleDateFormat. %)](.format(p"km")(.parse(p"h m a")s))))
;                                                     Parse the 3 pieces ^
;                          Format into "squished" format ^

Basically the Java answer. Input must be in the format 12 34 pm

You can shave it to 99 by using mod: #(let[[h m[i]](clojure.string/split % #" ")h(mod(Integer/parseInt h)12)](str(if(= i\p)(+ h 12)h)m)) — and shave another byte by moving if inside +: #(let[[h m[i]](clojure.string/split % #" ")h(mod(Integer/parseInt h)12)](str(+(if(= i\p)12 0)h)m))

Oh, and then just inline h for 96B: #(let[[h m[i]](clojure.string/split % #" ")](str(+(if(= i\p)12 0)(mod(Integer/parseInt h)12))m))

@BRFennPocock Cool, thanks. I'm about to start work, so I don't want to start fiddling with it now. I'll update it tonight. Thanks again.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Can this number be written in (3^x) - 1 format?
Challenge:
Create a program that accepts a positive integer and checks if it can be written in the form of (3^x)-1, where X is another positive integer.
If it can, output X
If it can't, output -1 or a falsy statement.
Example inputs/outputs
Input:
2

It can be written as (3^1) - 1, so we output x which is 1
Output:
1

Input:
26

26 can be written as (3^3) - 1, so we output x (3)
Output:
3

Input:
1024

1024 can't be written in the form of (3^x) - 1, so we output -1
Output:
-1

This is code-golf so least amount of bytes wins

Related OEIS: A024023

I ask to output X because I believe it's more challenging that way. Simply finding if it  is of format 3^x - 1 would be too easy for a challenge, in my opinion.

Maybe instead of -1 can we output some other distinct falsy value?

Yes you can. I edited my question, and now you can output a falsy value.

Would this kind of "magic formula" make sense? if (OEIS Sequence contains the number) return number; else return -1

Can 0 be returned instead of -1, seeing as the result will never be 0 (because X has to be positive)?

Unless if it's a falsy statement in your programming language, then no.

You said it should output -1 or falsy, so why is -1 invalid?

@devRicher I never said -1 is invalid, I answered to FlipTack who asked if 0 is valid.
Also I didnt understand your question. What do you mean if oeis sequence contains the number. The sequence for 3^x-1 is obviously infinite

May I want the number to be input in ternary?

@JanDvorak No you may not. Most programming languages can't accept base3 numbers / convert decimal to ternary or vice versa easily  (having a built-in method) so it would be unfair for them

How large of a number does our program need to support?

having to handle non-negative intergers would make 0  3^0-1  a valid output and thus not useable as false,

anyone thinking of using log() in their answer should confirm it giives the correct answer 5 when 242  is input.

@AlexL. The input should only be limited by memory to store the number. If the algorithm would work with any number in real life, it would be fine to use any integer max value.

does that mean bignums, or is it ok to use a normal integer type? and if so how small?

@Jasen Just use the "average" integer size. By average I mean, not "long", not "short". Eg, in VB.NET you have int16, int32, int64. In that case, you would use int32. Of course, if you want to use "long" becase it is less bytes, go ahead. Size doesnt matter, if you use something that was designed to store numbers.

Mathematica, 21 16 bytes
-1&@@Log[3,#+1]&

Makes use of Mathematica's symbolic computation. If #+1 is a power of three then Log[3,#+1] will compute an integer result which is an atomic value. Otherwise we'll get Log[#+1]/Log[3] as is. Since this is not an atomic value, it's an expression which is always of the form head[val1,val2,...]. In this case it's actually something like Times[Power[Log[3], -1], Log[#+1]].
We distinguish between the two cases by applying another function to the result. What applying really does is that it replaces the head part of an expression. Since integer results are atomic, applying any function to them does nothing at all. In particular f @@ atom == atom.
However, in the other case, the head does get replaced. The function we're using is -1& which is a simple function that ignores its arguments and returns -1. So we get something -1&[Power[Log[3], -1], Log[#+1]] in non-integer cases, which evaluates directly to -1. Special casing via magic.

Haskell, 35 bytes
f x=last(-1:[i|i<-[1..x],3^i-1==x])

Usage example: f 26 -> 3.

PS: Try it online! supports Haskell! (Nice answer btw!)

Python, 46 44 bytes
lambda x:max(n*(3**n-1==x)for n in range(x))

Try it online!
In this case, 0 would be the falsy value.  Thanks to @mbomb007 for pointing out my incorrect output as well as a 2 bytes no [] savings.

you can rewrite as [n for n in range(x)if 3**n-1==x] for -4 bytes, empty list as falsy

Fixed, thank you!  @Rod then it would return [n] instead of n I think

@nmjcman101 that shouldn't be a problem

@Rod I'd prefer adhering strictly to spec for now

@Rod If outputting an integer is required, you cannot output it in a list unless the OP specifically allows it.

Jelly, 5 bytes
R3*’i

Outputs x or 0 (falsy).
Try it online!
How it works
R3*’i  Main link. Argument: n

R      Range; yield [1, ..., n].
 3*    Map each k to 3**k.
   ’   Decrement the results.
    i  First index of n (0 if not found).

05AB1E, 7 bytes
3IÝm<¹k

Try it online!
Explanation
3        # push 3
 I       # push input
  Ý      # range [0 ... input]
   m     # 3^[0 ... input]
    <    # -1
     ¹k  # find index of input, return -1 if not found

05AB1E is apparently good at base conversion is this really the best approach?

@Jasen: My attempts with base conversion all turned out longer. If there is a better way than this I'm not seeing it. Feel free to prove me wrong though :)

fair enough, I've only read the description of the language, and, so  expected to see a 5 byte solution....

@Jasen <3zm©.ïi® is the closest I've got not using ranges like he did.

3DÝms<k... Nevermind... Can't shave off one more byte, could of sworn I could.

@carusocomputing: I'm pretty sure this is the minimum count using this strategy. Haven't found a different strategy able to improve on it, but it could be possible.

Brachylog v1, 8 bytes
,3:.^-?,

Try it online!
Outputs the value if true and false. if this is impossible.
Explanation
This is a direct transcription of the given relation:
,     ,      (Disable implicit unification)
 3:.^        3^Output…
     -?              … - 1 = Input

You can almost golf this down to 7 bytes as +~^r~:3, but unfortunately ~: doesn't do what you might expect (likely because : is syntax rather than a builtin), and seems to be treated identically to :.

@ais523 That's correct, : is a control symbol, and ~ only works on predicates.

Prolog, 20 bytes
d(A,X):-A#=(3**X)-1.

This language is cool as hell.
| ?- d(1024,X).

no
| ?- d(26,X).

X = 3

yes
| ?- d(2,X).

X = 1

yes

Perl, 31 bytes
say grep{3**$_-1==$i}0..($i=<>)

Requires -E flag to run:
perl -E 'say grep{3**$_-1==$i}0..($i=<>)' <<< 26

Explanations:
grep{3**$_-1==$i}0..($i=<>) returns a list of the elements of the range 0..$_ (ie. from 0 to the input) that satisfies the test 3**$_-1==$i. Only one element at most can satisfy this test, so this instruction will return an array of 0 or 1 element. We then print this list: either the X or nothing (which is falsy).

Python 2, 41 bytes
f=lambda n,i=0:i*0**n or n%3/2*f(n/3,i+1)

A recursive function that returns 0 for non-matching inputs. Repeatedly floor-divides the input by 3, counting the number of steps in i, which is output in the end. But, if any step produces a value n that isn't 2 modulo 0, the number was not of for 3^i-1, so the output is multiplied by 0.

Pyth, 11 bytes
?-JjQ3 2ZlJ

Converts to base 3 and checks equality to [2, 2, ..., 2].

You can reduce this by one byte with ?-2JjQ3ZlJ, since <col> <num> and <num> <col> are interchangeable for - in Pyth.

Processing, 60 56 bytes
void q(float n){n=log(n+1)/log(3);print(n>(int)n?-1:n);}

Outputs -1 if falsy.
Explanation
void q(float n){              // n is input
  n=log(n+1)/log(3);          // finds X in 3^X+1=n as a float (here we'll storing that in n)
  print(n>(int)n?-1:n);       // checks if the float is greater than
                              // the number rounded down (by int casting)
                              // if it is greater, output -1
                              // otherwise output X
}

void is 1 byte shorter than using float, so that's why this function directly outputs instead of returning a value.
Alternative Solution
void z(float n){int c=0;for(++n;n>1;c++)n/=3;print(n==1?c:-1);}

for 63 bytes, but I think this alt can be golfed to be shorter than the original solution. I'm working on it.

@FlipTack Yeah, I knew it wouldn't be in Java. I just asked since I wasn't sure that Processing hadn't added something along those lines. The "distinct value" to be used was -1 though, not 0. It's been changed since, though, so I'll probably clean up my comments about it.

Wait, so can I return 0 now?

I'd still say no. The question gives an alternative integer value to use if falsy, but 0 is never falsy in Java/Processing that I know of.

I thougt Processing was supposed to be less versbose than Java

@Pavel But I don't use lambdas :/

does it work with 242 as input (result 5)?

@Jasen Yes, it outputs 5 for 242 as input

JavaScript (ES7), 38 36 34 bytes
f=(n,k=33)=>3**k-n-1&&--k?f(n,k):k

Or just 30 29 bytes if it's OK to exit with an error on failure:
f=(n,k)=>~(n-3**k)?f(n,-~k):k

Test

f=(n,k=33)=>3**k-n-1&&--k?f(n,k):k

console.log(f(177146))
console.log(f(847288609442))
console.log(f(5559060566555522))
console.log(f(123456))

Java 8, 37 58 67 bytes
i->{String s=i.toString(i,3);return s.matches("2*")?s.length():-1;}

This lambda fits in a Function<Integer, Integer> reference and uses the simple base 3 trick.
This time it should work correctly.

Wouldn't that only print True or False when it can be written in the format? But I asked for the exponent when the result is True

That's genius! +1 for a very clever approach

This is clever... i believe you can remove the parens and just make it i->. Also, if you take i as a Long, you can then use a.toString(...) (ides will give some warnings about using static functions incorrectly, but should compile). However, as OP said, you need to return the value, not just True or False.

If the lambda is stored in a different function type then the static trick works. I also fixed the return value. I must have missed that part.

R, 24 bytes
A different approach from plannapus' answer, and one byte shorter!
match(scan(),3^(1:99)-1)

Generates all integers from 3^1-1 to 3^99-1, and checks if stdin matches. If so, it returns the index at which it matches, which is x. If not, returns NA as falsy value.
Incidentally, it will accept multiple values as input, and test all of them, which is a neat feature.

Perl 6,  25  24 bytes
{first $_==3** *-1,0..$_}

Try it
{first $_==3***-1,0..$_}

Removing the space after ** works because it is longer than the other infix operator that could match *.
So …***… is parsed as … ** * … rather than … * ** ….
Try it
Expanded:
{  # bare block lambda with implicit parameter ｢$_｣

  first
    $_ == 3 ** * - 1,   # WhateverCode lambda
    #          ^- current value

    0 .. $_             # a Range up-to (and including) the input

}

Husk, 4 bytes
£İ3→

Returns 0 if there's no such x, try it online!
Explanation
This works because £ assumes the list to be sorted and aborts the search once it sees a larger element:
£İ3→  -- implicit input N, for example: 80
   →  -- increment N -> 81
 İ3   -- list [3,9,27,81…
£     -- if it's in the list return index; -> 4
      -- else return 0

PowerShell Core, 42 40 bytes
param($a)1..$a|?{"3*"*$_+"1-1-eq$a"|iex}

-2 bytes thanks to mazzy, by replacing the [Math]::Pow, nice one!
Try it online!

I also tried the log approach but couldn't make it shorter: (0,($t=[math]::log(1+"$args",3)))[$t-eq[int]$t]

40 bytes :)

05AB1E, 9 bytes
DÝ3sm<Q1k

Try it online!
Prints -1 for falsy.
D         # Duplicate the input
 Ý3sm     # Push [0 .. input]^3 (e.g. [0^3, 1^3, 2^3, 4^3 ...])
     <    # subtract 1
      Q   # push a 1 everywhere that equals the input, and 0 everywhere else
       1k # push the index of the 1, or -1 if not found
          # implicit output

Japt, 11 bytes
o æ@U+1¥3pX

Try it here.
Big thanks to ETHproductions for helping!

Python 3, 74 66 64 bytes
-10 bytes thanks to @mbomb007, @FlipTack and @nmjcman101
from math import*
def f(n):x=ceil(log(n,3));print((3**x-1==n)*x)

You can put all of your code on one line and use from math import*. Also return n==3**x-1and x.

65 byte solution

@mbomb007 Functions are allowed to print the result to STDOUT, so you can change that return to a print.

If you present this as a SageMath solution rather than a Python one, you can drop the first line altogether.

Along with the other reduction to 65 bytes, you can use import math and math.ceil for a single byte.  Also you can turn 3**x-1==n and x to x*(3**x-1==n)

@nmjcman101 math.log is also in play, so from math import * compensates.

@FedericoPoloni please post your golf suggestion as comment, you can also add a link to an online compiler with the golfed code, but edits on others' answers are not a good pratice

@Rod, the suggested Sagemath solution, though related with Python, relates to another software entirely, making the edit suitable for a new answer altogether in this case.

@dfernan yep, I was just showing him why his (suggested) edit on your answer was rejected

@Rod I have already posted it as a comment, but it was ignored. I suggested it as an edit to make it more explicit. I will post it as a new answer now, as per dfernan's suggestion.

MATL, 8 bytes
3i:^qG=f

This outputs the number x if it exists, or otherwise outputs nothing, which is falsy.
Try it online!
Explanation
3    % Push 3
i    % Input n
:    % Range: gives `[1 2 ... n]
^    % Power, element-wise. Gives [3^1 3^2 ... 3^n]
q    % Subtract 1, element-wise. Gives [3^1-1 3^2-1 ... 3^n-1]
=    % Test for equality. Contains 'true' at the position x, if any,
     % where 3^x-1 equals n
f    % Find. Gives index of the 'true' position, which ix x; or gives
     % an empty array if no such position exists. Implicitly display

Bash / Unix utilities, 37 35 bytes
bc<<<`dc<<<3o$1p|grep ^2*$|wc -c`-1

Try it online!
Uses dc to convert to base 3, checks that the resulting string is all 2s, counts the number of characters (including a newline), and then uses bc to subtract 1.
If the number in base 3 is not all 2s, then grep outputs nothing (not even a newline), so the character count is 0, and subtracting 1 yields -1.

C compiled with Clang 3.8.1, 53, 52, 54, 51 Bytes
n;f(y){y++;for(n=0;y%3==0;y/=3)n++;return y^1?0:n;}

@SteadyBox already posted a solution in C, but I'm using a different approach.
@Thanks to Jasen for helping save bytes.

yeah, but does it work? comparing floats for equality is often a recipe for unexpected failure (try large inputs)

@Jasen Hmm, haven't tried that, but in C log returns double so maybe it might work.

double is a type of floating point value so he problem persists.

seems to work ok  for 3^19 which is probably large enough.

@Jasen It doesn't work for 3^10

use a 16 bit compiler then :)

@Jasen Check my edit, interestingly enough, if I put the result from log into a float it works even for larger numbers.

with float fails on 4782967 (3^14) here  with double on 243 (3^5-1)

@Jasen Check my edit, this time I tried with simple divisions, works for all powers up to 19.

yeah, that works. It now  seems quite similar, but superior, to my answer,  y==1 and y+=1 can both be golfed further. Also, 0 is allowed instead of -1. that would get you to 51

@Jasen Thanks for helping me save bytes.

y%3==0 => y%3<1

return y^1?0:n; => return--y?0:n; if want to keep the word return; or yo can use some operation to give EAX the value, and directly go out

Ruby, 30 bytes
Returns nil (a falsy value) if no number was found. [Try it online]
->n{(0..n).find{|i|3**i-1==n}}

C, 56 bytes
 n;f(a){n=0;for(a++;!(a%3)&&(a/=3);++n);return --a?-1:n;}

add one to the input and then repeatedly divide by three until a remainder is found, if the one is reached return the count of divides else -1

Save one byte with a%3<1 instead of !(a%3). One more with 0 for falsy.

Assuming you're using GCC to compile you can save a total of 10(11) bytes: you don't need to initialize n to zero if you know you'll call this function only once since then n will be zero by default (because it's global) - that's 4 bytes less; also you don't need the return statement, by writing a=--a?-1:n; you'll save 5 bytes. if a non-void function has no return, it'll just use the last assignment. Also what @Titus said.

Suggest a%3?0:(a/=3) instead of !(a%3)&&(a/=3)

Pyt, 10 9 bytes
←⁺3ĽĐĐƖ=*

Explanation:
←                Get input
 ⁺               Add one
  3Ľ             Log base 3
    ĐĐ           Triplicate top of stack
      Ɩ          Convert top of stack to integer
       =         Check for equality between top two on stack
        *        Multiply by log_3(input+1)

Saved a byte by using the increment function instead of explicitly adding 1

in what code page is that 9 bytes? (in UTF-8 it's 17 bytes)

APL (Dyalog Unicode), 12 bytesSBCS
Anonymous tacit prefix function.
(⊢×⌊=⊢)3⍟1+⊢

Try it online!
1+⊢ increment
3⍟ log3
(…) apply the following function:
 ⌊=⊢ is the floor equal to the argument? (0 or 1)
 ⊢× multiply the argument by that

C, 42 Bytes, optimized from Wade Tyler's
n;f(y){for(n=0;y%3>1;y/=3)n++;return!y*n;}

Try
C, 37 Bytes, without return
n;f(y){for(n=0;y%3>1;y/=3)n++;n*=!y;}

Try
n is global but (I)MUL can only have its dest operand in a register, so have to put into EAX(the usual choice) and mov there
JavaScript 6, 32 Bytes

f=(y,n)=>y%3>1?f(y/3|0,-~n):!y*n
;[1,2,3,8,12,43046720].forEach(x=>console.log(f(x)))

If the "falsy" need to be same, 33 Bytes:
f=(y,n)=>y%3>1?f(y/3|0,-~n):!y&&n

Vyxal r, 6 bytes
ɾ3e‹ḟ›

Try it Online! The r flag reverses the arguments of all functions.
Explanation:
ɾ       # Range from 1 to n
 3e     # 3 ^ each number in the range (not n ^ 3 because of the r flag)
   ‹    # Decrement
    ḟ   # Index of the input
     ›  # Increment because ḟ is 0 indexed

Vyxal, 6 bytes
3¨e‹ḟ›

Try it Online!
Decided this was different enough from the other Vyxal answers to post.
    ḟ  # find the index of the input in
3¨e    # all powers of 3
   ‹   # -1
     › # and add 1 to that index

Brachylog, 6 bytes
;3^₍-₁

Try it online!
Takes input through the Output variable.
Explanation
;3         [?, 3]
  ^₍       3^?
    -₁     3^? - 1 = Input

This will unify ? with the right value if possible, and output false. otherwise.

Python, 64 bytes
Outputs False if the number cannot be written in that format.
def f(n):L=[3**x-1for x in range(n)];print n in L and L.index(n)

This also works in 64 bytes, and prints empty string as a falsy output:
def f(n):
 try:print[3**x-1for x in range(n)].index(n)
 except:0

A creative solution for 65 bytes, outputting 0 for falsy:
lambda n:-~",".join(`3**x-1`for x in range(n+1)).find(',%s,'%n)/2

Does not output x nor -1.

The program should output x instead of n in case of a match.

No, it should output the positive integer that when replaced with X, you get the input. The question refers to X as a variable, not as a string

@P.Ktinos Fixed it.

Octave, 23 bytes
@(x)find(3.^(1:x)-1==x)

Verify all test cases!
Explanation:
This is an anonymous function that takes a positive integer x as input. .^ is element-wise power in Octave, so 3.^(1:x) is 3^1, 3^2, 3^3 .... Subtracting 1 gives 3^1-1, 3^2-1, 3^3-1 ... which can be compared to x.
find(a,b) takes a vector a as input, and attempts to find the scalar b in that vector and returns its index. If it's not found then it will output an empty matrix []. An empty matrix is a falsey value in Octave.
find(3.^(1:x)-1==x) searches for x in the vector 3^1-1, 3^2-1, 3^3-1 ...
and attempts to return its index. If it's not in the vector then it returns an empty (falsey) matrix.

GolfScript, 11 bytes
~..3\?\)%!*

Try it online!
Uses the fact that 3n is divisible by n+1 if and only if n+1 itself is a power of 3.  Outputs its input n if n+1 is a power of 3, otherwise outputs 0 (which is falsy in GolfScript).
De-golfed:
~             # eval the input, converting it from string to integer
 ..           # make two copies of the input number
   3\?        # raise 3 to the power of the input number
      \)%     # reduce the result modulo the input number plus one
         !    # boolean negate the result, mapping 0 to 1 and all other values to 0
          *   # multiply the input number with the result

Ps. Here's a simple test harness that runs the code above (minus the initial ~, which is not needed since the inputs are already numbers) on all integers from 0 to 9999 and prints those for which it returns a truthy result:
10000,{ ..3\?\)%!* },`

The output of this program should be:
[2 8 26 80 242 728 2186 6560]

(The output doesn't include 0 because, even though the formula used does correctly detect it as one less than a power of 3, the result is still 0 × 1 = 0, and thus falsy.  Fortunately, 0 is not a positive integer, and thus isn't a valid input for this challenge anyway.)

c++ 60 bytes
int f(n){float o=log1p(n)/log(3);return o/floor(o)!=1?-1:o;}

explanation:
int f(n){
  float o=log1p(n)/log(3);       // eval for x using log3 function
  return o/floor(o)!=1?-1:o;     // if no remainder output X
}

I think you don't have to use uint16_t. You can use normal int.

I guess I could to save a few bytes but it seemed to me that if I wasn't safeguarding against negative integer input then I wasn't following the guidelines.

this compile to me: int f(n){float o=log1p(n)/log(3);return o/floor(o)!=1?-1:o;}

@mreff555 You don't need to safeguard against negative input, you can assume positive input.

R, 34 25 bytes
a=log(scan()+1,3);a*!a%%1

Calculate the base 3 logarithm of the input + 1. Test if the result is an integer, if it is it outputs it, if not it outputs 0 as falsey value.
Thanks to @Billywob for the extra 9 bytes off!
Test cases:
> a=log(scan()+1,3);a*!a%%1
1: 1024
2:
Read 1 item
[1] 0

> a=log(scan()+1,3);a*!a%%1
1: 26
2:
Read 1 item
[1] 3

Old version at 34 bytes which outputs -1 as falsey value.
a=log(scan()+1,3);`if`(!a%%1,a,-1)

If you do a*!a%%1 it will output a if true and 0 otherwise and you can skip the if thing.

The spec says "If it can't, output -1 or a falsy statement." and 0 is interpreted as FALSE in R so I would say it's valid.

Pyth, 10 bytes
*J@hQ3!%J1

Try it here!

Pyke, 9 6 bytes
3m^Qh@

Try it here!
3m^    -  map(3**i, range(input))
     @ - V in ^
   Qh  -  input + 1

Old 9 byte version:
b3'l}\2q*

Try it here!

Julia, 30 bytes
n->findfirst(n.==3.^(0:n)-1)-1

It's a simple function - it creates a vector that has a true only in the corresponding position in 3^a-1, where a is a vector containing integers between 0 and n. It finds the "first" position that is true and subtracts 1 (if it's all false, the find evaluates to zero, and it returns -1).
As 0:n has 0 in the first spot, the subtract 1 corrects for indexing and also enables the -1 false response.

Pyth 8 bytes
xm^3dUQh

     UQ  # generate all values 1..Q (Q is the input)
 m^3d    # map 3^d over this ^ list
x      h # find the input+1 (hQ) in the result of the last command

Try here

C, 81 bytes
i,j,k;f(n){for(i=0;++i<n;){for(k=3,j=0;++j<i;k*=3);if(n==k-1)return i;}return-1;}

I think you save bytes by using pow(3,i) instead of defining your own.  Gcc complains about the missing #include <math.h> but compiles it anyway.  I did have to cast to int.  You also may be able to gain some by adding an r variable, initializing to -1, and then if(n==k-1)r=i;}return r;}

@nmjcman101 Thanks, but pow() produces some incorrect results because of floating point inaccuracy. (When cast to int, 2.9999 will be 2, not 3). Adding a variable r sounds like a good idea, but it actually results in a 2 bytes longer code.

yeah, log doesn't work, pow probably won't either.

Japt, 8 bytes
o m!³a°U

Try it online!
This code expands into the following:
Uo m!p3 a++U

Uo            // Create the range [0...U).
   m!p3       // Map each item X to 3**X.
        a++U  // Take the index of U+1. Returns -1 if it doesn't exist.
              // Implicit: output result of last expression

Very nice solution.

C, 76 bytes
main(i,a,c){scanf("%d",&a);for(c=0,++a;i<a;i*=3,++c);printf("%d",(i==a)*c);}

Sagemath, 45 bytes
This is simply @dfernan's solution repackaged as Sagemath (which is basically Python + some math libraries loaded by default and syntactic sugar).
In Sagemath, we can avoid the import math and we can use ^ for exponentiation, so we save a few chars.
def f(n):x=ceil(log(n,3));print((3^x-1==n)*x)

Test it online

Python 2, 34 bytes
lambda n:(~n>>3**n%-~n*n)**4/80%80

Try it online!
Works for all Python ints, up to at least 2^100.

Pip, 13 bytes
aTB:3MNa=2&#a

Try it online!
Explanation
               a is 1st command-line argument (implicit)
aTB:3          Convert a to base 3 and assign back to a
     MNa=2     Does the min of a's digits equal 2?
          &    Logical-and
           #a  Length of a
               If there are non-2 digits, we get the falsey value 0; otherwise, we get
               the number of digits

05AB1E, 6 bytes
>3.n.ï

Try it online!
> increments, 3 pushes a 3 to the stack, .n find the logarithm with base 3, .ï checks if it is equal to its integer part.
Returns 0 for falsy: If it can't, output -1 or a falsy statement.

APL NARS, 14 chars or 28 bytes
{r×r=⌊r←3⍟1+⍵}

Test:
  f←{r×r=⌊r←3⍟1+⍵}
  f 2
1
  f 26
3
  f 1024
0

This is 28 bytes in NARS, but exactly the same solution is only 14 bytes in Dyalog APL. Also, you can save two bytes by conversion to tradfn, r×r=⌊r←3⍟1+⎕, letting the program prompt for input.

@Adám i prefer functions

APL (Dyalog), 11 bytes
⊢|⊢⍳⍨¯1+3*⍳

Try it online!
Uses ⎕IO←0.
How?
⍳ - range of 0 to n-1.
3* - raise 3 to the power of each element.
¯1+ - decrement each by 1.
⊢⍳⍨ - search the index of n in that list (if not exists, this would return the maximum index plus 1 - which is n.
⊢| - modulo by n. This would keep the index, if found, and zero-out numbers not contained in the list that would produce n % n = 0.

APL (Dyalog), 14 bytes
(∧/×≢)2=3⊥⍣¯1⊢

Try it online!

"26 can be written as (3^3) - 1"  124 can be written as (5^3)-1 but your code for 124 not print 5 print 0

Ok I confuse exponent and base

@RosLuP you mind deleting the comments? people use to DV without much thinking when seeing these

Befunge-93, 26 bytes
&1+>:3%v
1+\^v-1_3/\
.@.$_

Try It Online
Prints 0 as the falsey.
How it Works
&1+... Gets the input and adds one
......
......

...>:3%v    Check if the number is divisible by 3
1+\^..._3/\ If not, divide the number by 3 and increment a counter
...         Repeat until the number is not divisible by 3

.........   If the final number is a one, print the counter
....v-1_... Else pop the counter and print a 0
.@.$_       End the program

Factor, 30 bytes
[ 1 + 3 over [0,b) n^v index ]

Try it online!
Port of Dennis' Jelly answer. The index word conveniently returns f (the only falsy value in Factor) when the item is not found.
[              ! anonymous lambda
  1 + 3 over   ! ( n+1 3 n+1 )
  [0,b)        ! ( n+1 3 {0..n} )
  n^v          ! ( n+1 {3^0..3^n} )
  index        ! 0-based index of n+1 in {3^0..3^n}; false if not found
]

Factor, 45 bytes
[ 3 >base dup [ 50 = ] all? swap length and ]

Try it online!
A base-conversion approach.
[                    ! anonymous lambda, accepting a positive integer n
  3 >base            ! ( str ) convert to base-3 string
  dup [ 50 = ] all?  ! ( str ? ) test if it is all 2's
  swap length and    ! ( len/f ) if true, return the length of str
                     ! otherwise return false
]

Japt -æ, 6 bytes
Outputs undefined, which is falsey, instead of -1.
NøÓ3pU

Try it

Vyxal, 7 bytes
›3•D⌊=*

Try it Online!
-1 thanks to Steffan.
A different approach that's annoyingly longer.
›       # Increment
 3•     # Log 3
   D⌊=  # Check if it's an integer
      * # Multiply by that

@Steffan I guess, although it's kinda ambiiguous as 0 is an allowed output.

tinylisp, 68 bytes
(d F(q((N A)(i(l N A)()(i(e A N)0(a 1(F N(a(a A A)A
(q((N)(F(a N 1)1

The solution is the anonymous function on the second line. Try it online!
Explanation
The function F does most of the work. It takes a target number N and an accumulator A. If N is a power of three, it returns the exponent; otherwise, it returns nil, which is a falsey value.
(d F               ; Define F
 (q                ; to be a function
  ((N A)           ; that takes arguments N and A:
   (i(l N A)       ; If N is less than A,
    ()             ; return nil
    (i(e A N)      ; Else, if A is equal to N,
     0             ; return 0
     (a 1          ; Else, add 1 to the result of
      (F N         ; a recursive call with the same N
       (a(a A A)A  ; and three times the A (A+A+A)

If N equals three to the X, the 0 base case will be reached at the Xth level of recursion, meaning that 1 will be added to it X times for a result of X. If the () base case is reached instead, 1 will be added to it some number of times, but adding a number to nil gives nil (and an error message).
The submission function is then just a wrapper around F:
(q          ; A function
 ((N)       ; that takes argument N:
  (F        ; Call F with arguments
   (a N 1)  ; N+1
   1        ; and initial accumulator 1

Thunno D, \$ 7 \log_{256}(96) \approx \$ 5.76 bytes
R3@1-Ah

Attempt This Online!
Explanation
R3@1-Ah  # D flag duplicates implicit input
R        # Push range(0, input)
 3@      # 3 ** each
   1-    # Decrement
     Ah  # Index of input in this list
         # (0-indexed, -1 if not found)

Nekomata, 5 bytes
3D←P∑

Attempt This Online!
3D      Convert to base 3
  ←     Decrement every digit
   P    Check if all digits are positive
    ∑   Sum

Stax, 6 bytes
ö♥ô·ô₧

Run and debug it
This unpacks to the following:
Stax, 7 bytes
f3s#vx=

Run and debug it
f       # filter over 1..input
 3s#    # 3^n
    v   # -1
     x= # is equal to the input

Outputs nothing if falsy

Common Lisp (SBCL), 83 50 bytes
(let*((i(read))(r(log(1+ i)3)))(if(=(mod r 1)0)r))

Old version:
(let((i(read)))(if(find-if(lambda(x)(not(eq x #\2)))(format()"~3R"i))()(log(1+ i)3)))

Feedback encouraged!

JavaScript (ES6), 40 bytes
f=(n,p=0,k=1)=>n<k?n>k-2&&p:f(n,p+1,k*3)

Returns false or the power. A simple port of @Arnauld's ES7 answer would have taken 43 bytes.

I think f=(n,p,k=1)=>n<k?n>k-2&&p:f(n,-~p,k*3) works and saves 2 bytes.

Java 7, 180 bytes
class A{public static void main(String[]q)throws Exception{int a,b=0;while((a=System.in.read()-48)>=0)b=b*10+(a);double k=Math.log(b+1)/Math.log(3);System.out.print(k%1==0?k:-1);}}

Really simple approach. Input, then add one, then log3 the number, and if it's a integer, print it; otherwise, print -1. Could use some work.
Only works up to (3^19)-1.

Why is this non-competing? The Non-Competing status is only reserved for languages or language features that were added after the challenge was posted.

As I said, size doesn't matter, so this can compete.

@KritixiLithos Oh okay. I wasn't aware of the exact meaning of Non-Competing. Thanks. Also, I'll update the title.

You can use interface A{...} and drop the public from main(). Why do you have (a) instead of a in the while loop. I think you can use float k=... instead of double k=.... Should be -5 bytes if I counted right.

@RomanGräf I appreciate your suggestions; however, none of them are of any use for me, unfortunately. Your first suggestion only works in Java 8, and there is already a far better Java 8 solution out there. I have (a) in the while loop because I am doing a comparison of an assignment statement, and assignment has the lowest priority on the order of operations and thus requires a set of brackets around it. Finally, I have double because Math#log returns a double and casting would obviously be much slower. Regardless, thank you for the suggestions, but I will not be incorporating them.

PHP, 36 47 bytes
If log(input+1,3) differs from its integer value, print 0; else print the logarithm:
<?=(0|$x=log($argv[1]+1,3))-$x?0:$x; (36 bytes) fails for 242.
<?=strstr($x=log($argv[1]+1,3),".")?0:$x; and <?=(0|$x=log($argv[1]+1,3))-$x>1e-7?0:$x; (41 bytes) may fail for larger $x.
This version is safe:
for(;3**++$x<$n=1+$argv[1];);echo$n<3**$x?0:$x;

1.Loop $x up from 1 while 3^$x is smaller than argument+1.
2.Print 0 if the expression is larger than input+1, $x else.
Takes input from command line argument. Run with -nr.

gives wrong answer for 242 input

@Jasen: The downvote was ridiculous, but it´s fixed now.

CJam, 11 bytes
ri3b_2-!\,*

Basically it determines if the number's trinary (base 3) representation contains only 2's, and if it does, outputs the number of 2's. It outputs 0 if the number is not only 2's.
Try it online!
Explanation
ri          e# Get input as an integer
  3b        e# Convert to base 3 (an array of the digits in base 3)
    _       e# Duplicate
     2-     e# Remove all 2's from the array
       !    e# Boolean negation. Yields 1 if the array contained only 2's (and is now
            e# empty), 0 otherwise
        \   e# Swap top 2 elements of stack
         ,  e# Take the length of the base 3 digits array
          * e# Multiply by the boolean value from before

"Trinary" is more commonly referred to as Ternary.

C 90 bytes
f(x){i=1;for(;i<x;i++){if((pow(3,i)-1)==x){printf("%d",i);break;}if(i==(x-1))puts("-1");}}

Ungolfed Version:
void f(int x)
{
  int i=1;
  for(;i<x;i++)
  {
    if((pow(3,i)-1)==x)
    {
        printf("%d",i);
        break;
    }
    if(i==(x-1))
        puts("-1");
  }
}

for x=1 what would return/print that above?

SmileBASIC, 32 bytes
INPUT X
X=LOG(X+1,3)?X*(X==X>>0)

Outputs 0 for false.

Cardinal, 91 bytes
%
:
+
~
v~d<
0  /{<
+  A #-?+M?"-1"@
+  !   @.-<
+  M #  M!/        <
>~ # ^  } \       +^%

According to the specifications of Cardinal, this shouldn't work for inputs above 255. However, due to the implementation in TIO accepting values over 255, it will work past 255 up to 3^34.
Try it online!
Explanation
%
:
+

Input + 1
~
v~d<
0  /{<
+  A
+  !
+  M
>~ # ^

While divisible by 3
#-?+M?"-1"@

Output -1 if not divisible by 3 or equal to 1 and end program
   .-<
#  M!/        <
   } \       +^%

Output counter for how many times the input + 1 has been divided by 3 before equalling 1

TI-Basic (TI-84 Plus CE) 17 15 bytes
logBASE(Ans+1,3)
Ansnot(Ans-int(Ans

All tokens used are one-byte except logBASE(,  which is two.
Explanation:
logBASE(Ans+1,3)   # inverse of 3^n-1 is log3(x+1)
Ansnot(Ans-int(Ans # if X is an integer, `X-int(x` is 0, so `not(X-int(X` is 1, which is multiplied by X
                   # if X is not an integer, `X-int(X` is not 0, so `not(X-int(X` is zero, which is multiplied by X
                   # last value evaluated is implicitly returned

QBIC, 18 bytes
:[a|c=3^b-1~c=a|?b

Explanation
:        Get 'a' from the cmd-line
[a|      FOR b=1; b<=a; b++  (this runs a lot longer than we need...)
c=3^b-1  Set c to be 3^b-1
~c=a     IF this is the input given
|?b      THEN print b
         END IF and NEXT are added implicitly

This would print multiple bs if it would be possible to have multiple solutions. Right now, it runs on after finding a solution. We could substitute ?b for _Xb to quit after finding a solution, but that adds a byte. Also, the FOR-loop [a| could be initialised as [a/3| to save us a lot of iterations, but that adds another 2 bytes.

Axiom,72 65 63 bytes
g(x:PI):INT==(z:=floor(y:=log(x+1.)/log(3.));y-z~=0=>-1;z::INT)

some test
(51) -> [[x,g(x)]  for x in [1,2,3,4,5,6,7,8,9,10,26,27,79,80,242]]
   (51)
   [[1,- 1], [2,1], [3,- 1], [4,- 1], [5,- 1], [6,- 1], [7,- 1], [8,2],
    [9,- 1], [10,- 1], [26,3], [27,- 1], [79,- 1], [80,4], [242,5]]

J, 14 bytes
[:(*>.=])3^.>:

Try it online!
Here's a variant using a range of powers and indexing (@Dennis's method).
(~:*])>:i.~3^i.

Here's a variant using base conversion (@orlp's method).
[:(#*&(*/)2=])3&#.inv

Perl 5 -p, 28 bytes
$_=(log$_+1)/log 3;$_*=!/\./

Try it online!
Outputs 0 as the error/falsy state.

Kotlin, 78 bytes
{val x=kotlin.math.log(it+1.0,3.0);if(kotlin.math.round(x)==x)x.toInt()else-1}

kotlin.math.log and kotlin.math.round imported, 54 bytes
{val x=log(it+1.0,3.0);if(round(x)==x)x.toInt()else-1}

Desmos, 31 bytes
l=log_3(x+1)
f(x)=0^{mod(l,1)}l

Try it on Desmos!

Brainlove, 51 bytes
+[[-(>>[-]--<<+)-(>>[-]--<<+)->+<]>[<+>-]>+<<-(-)+]

Try it online
Just an increment and then iterative division by 3. The input is in the starting cell (cell 0) and output in cell 2. The printing in unary is just for demonstration and testing and is not a part of the actual solution. For falsy returns 255, as it is the best representation of -1 and due to limited cell space it cannot be the X.


text:
Stage Fright Snowman!
Help! Here is my good friend Mr. Snowman:
\(.,.) < Hello!
 ( : )>

He is an amazing dancer, but he tends to get stage fright. He knows all the moves, but just needs someone to tell him which moves to do. Here are all of his moves:
Arms Up
\(.,.)/
 ( : )
Arms Down
 (.,.)
<( : )>
Right Arm Up
\(.,.)
 ( : )>
Left Arm Up
 (.,.)/
<( : )
Hand Stand
 (   )
/(.,.)\

It takes Mr. Snowman about a full second to get to the next move. So, keep that in mind when you are making the dance routine. He needs a program that will help him know which moves to do.
Challenge
Mr. Snowman starts every performance with his arms down. Then he waits a second before taking in some form of an array with a list of the moves for Mr. Snowman to complete. This can be done in any format that suits your interface/language just make sure that you tell Mr. Snowman what each item corresponds to which move. Since Mr. Snowman will be on stage dancing, the fewer the bytes the better! Each time Mr. Snowman makes a move wait a full second until telling him what the next move will be. Also, at the end of the performance Mr. Snowman will sadly melt because frankly he is a snowman.
<empty line>
 _____

TL;DR

Start by displaying Mr. Snowman in the "Arms Down" move.
Take in an array (can be of any format) and indicate in the answer how each item in the array corresponds to which moves.
Each move takes a full second to transition to, including the melting transition. You do not have to be exactly one second, but try to get close.
At the end of the program display Mr. Snowman as a melted snowman. That is an empty line followed by a space and five underscores.
Each time a move is displayed clear the previous (or whatever looks like clearing) to make it look like Mr. Snowman is dancing.

This is code-golf; may the shortest answer in bytes win!

Very closely related to that one. Since my vote is a hammer, I'm not going to vote unless there are others that agree.

Thought it might be different enough from that challenge due to the input and that there are start and end conditions for what is displayed. But if you all think differently, I do not mind taking it down.

This challenge takes a list of moves as input whereas the bird challenge randomly generates moves. Imo this is a nontrivial difference but I don't want to see a large influx of "animate some ascii art" challenges. That all being said, this seems ok to me.

Since I am new, I do not see what is wrong with having "animate some ascii art" challenges that vary based off of that particular problem. Because you could say the same for "is n in this sequence" challenges which are all really the same, but based off of that problem changes the challenge. Is there something inherently wrong with these types of challenges?

@TimmyD Hate to use something that might have been wrong to begin with but, are these two questions not considered the same if this one is considered the same as bird dancer? Asciimation Jumping Jacks and Blinking Twelve

@tkellehe: The basic problem is just that with these animated ASCII-art problems, techniques useful for solving one problem will likely solve all the rest too, so that once one problem's been posted, there's no real creativity in solving more along the same lines. That doesn't happen as much with sequence questions because code for generating one sequence, and for generating another sequence, tends to look fairly different. That said, although I'm inclined to call it a duplicate, I'm not sure, so I haven't voted either way.