通用Lisp(151122字节)
好的,CL并不意味着“简洁”,但我只是感到惊讶,它并不是最冗长的。
这是122字节的版本,需要固定位置输入。0145pm或145p可接受(在第一个字符位置的前导空格)。
(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)))
打印:
(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)))
更好但是更大
仅使用Common-Lisp包装。接受(仅)以整数小时(带或不带前导0),文字:,两位数分钟以及可选的尾随am或pm(仅小写)的形式输入。允许在时间周围和AM / PM周围留空格,但不能在:。之后紧接空格。
(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)))
测试:
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 函数定义:
(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)))
消除混淆:
(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))))