Java를 생성하십시오.


14

상사는 다음과 같은 코드를 작성하기를 원합니다.

public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

(Martin Smith, /codereview//a/117294/61929 )

효율적이고 타이핑하기는 쉽지 않습니다. 수행해야하는 키 누르기 횟수를 최소화하기 위해이 함수를 출력하는 짧은 프로그램이나 함수 (또는 메소드)를 작성하거나 문자열을 출력으로 반환합니다. 또한 모든 유니 코드 8.0에 필요한 120,737 개의 키가있는 고유 한 사용자 정의 풀 레인지 유니 코드 키보드 가 있으므로 키 누르기 대신 유니 코드 문자를 계산합니다. 또는 언어에서 유니 코드 소스 코드를 사용하지 않는 경우 바이트입니다.

프로그램이나 함수는 입력해야합니다.

설명 및 편집 :

  • 마지막 뒤의 후행 공백 3 개를 제거했습니다. }
  • 후 단일 후행 공간을 제거했습니다. return
  • 함수 / 메소드에서 출력 문자열을 반환하는 것은 괜찮습니다.

12
0==Math.log10(input)%1
SuperJedi224

7
" 우리는 유니 코드 문자를 세고 "라고 말한 다음 즉시 " 또는 바이트 "라고 말합니다 . 어떤거야?
Doorknob

2
당신이 선호하는 것, 즉 가장 낮은 점수를주는 것. 텍스트 소스를 사용하지 않는 언어를 허용하는 바이트를 추가했습니다.
Filip Haglund

1
while(input%10==0) input/=10; return input == 1;
PSkocik

4
05AB1E는 유니 코드가 아닌 바이트 인 Windows CP1252를 사용합니다. 나는 표준 규칙을 목표로하고 있지만 항상 틀렸다는 말을 듣는다.
Filip Haglund

답변:


15

PostgreSQL, 158 자

select'public static boolean isPowerOfTen(long input) {
  return
   '||string_agg(' input == 1'||repeat('0',x)||'L','
  ||')||';
}'from generate_series(0,18)x

나는 코드 골프 답변으로 사용되는 RDBMS를 본 적이 없다. +1
Chris Cirefice

@ChrisCirefice SQL은 실제로이 사이트에서 다소 일반적입니다. (또는 적어도 예상보다 더 일반적입니다.)
Alex A.

@AlexA. 나는 SQL 응답 : 본 적이 그래서 흠, 잘 PCG 내 덜 자주 SE 사이트 중 하나입니다
크리스 Cirefice

7

Vim 97 키 스트로크

ipublic static boolean isPowerOfTen(long input) {
  return
  || input == 1L<esc>qyYpfLi0<esc>q16@yo}<esc>3Gxx

글쎄, 나는 오늘 vim을 생산하는 vim을 사용하고있다.


교체 fL로하는 것은 $당신에게 키 입력을 절약 할 수있다
새는 수녀

또한 세 번째 줄 input == 1L은 1 바이트 씩 잘못 정렬되어 있습니다.
Leaky Nun

마지막 x으로 변경 r<sp>한 다음 키 입력 수는 변경되지 않습니다
Leaky Nun


7

CJam, 52 자

YA#_("𐀑򀺸󆚜񸎟񜏓񞍁򛟯󩥰󾐚򉴍􍼯𹾚򶗜򳙯󭧐񹷜񊽅𸏘򴂃򦗩󧥮𤠐𰑈򶂤𘏧󔆧򇃫󡀽򊠑񊩭򯐙񛌲񊚩𤱶𻺢"f&bY7#b:c~

온라인으로 사용해보십시오!

스테이지 1

유니 코드 문자 U + 10000 ~ U + 10FFFF를 사용하여 단일 문자로 20 비트를 인코딩 할 수 있습니다. CJam은 내부적으로 16 비트 문자를 사용하므로 각 문자는 한 쌍의 서로 게이트 ( U + D800에서 U + DBFF까지, U + DC00에서 U + DFFF까지)로 인코딩됩니다.

1023으로 각 대리 문자의 비트 단위 AND를 가져 와서 인코딩하는 10 비트 정보를 얻습니다. BMP 외부의 임의의 유니 코드 문자 문자열을 ASCII 문자열로 디코딩하기 위해 결과 배열을 기본 1024에서 기본 128로 변환 할 수 있습니다.

코드는 다음을 수행합니다.

YA#    e# Push 1024 as 2 ** 10.
_(     e# Copy and decrement to push 1023.

"𑅰󻢶񹱨񉽌񍍎񄆋򎿙򧃮񑩹󠷽􂼩􉪦񭲣񶿝򭁩󭰺􄔨񍢤𘎖񮧗򦹀𹀠񐢑񜅈𠟏򘍎󾇗򲁺􅀢򅌛񎠲򦙤򃅒𹣬񧵀򑀢"

f&     e# Apply bitwise AND with 1023 to each surrogate character.
b      e# Convert the string from base 1024 to integer.
Y7#    e# Push 128 as 2 ** 7.
b      e# Convert the integer to base 128.
:c     e# Cast each base-128 to an ASCII character.
~      e# Evaluate the resulting string.

2 단계

위의 디코딩 프로세스는 다음 소스 코드 ( 98 바이트 )를 생성합니다.

"public static boolean isPowerOfTen(long input) {
  return
   ""L
  || input == ":S6>AJ,f#S*"L;
}"

온라인으로 사용해보십시오!

코드는 다음을 수행합니다.

e# Push the following string.

"public static boolean isPowerOfTen(long input) {
  return
   "

e# Push the following string and save it in S.

"L
  || input == ":S

e# Discard the first 6 characters of S. The new string begins with " input".

6>

e# Elevate 10 (A) to each exponent below 19 (J).

AJ,f#

e# Join the resulting array, using the string L as separator.

S*

e# Push the following string.

"L;
}"

당신은 유대교와 같은 SE 사이트는 사이트의 유니 코드 지원을 스트레스 테스트 것들로 예상 할 수 있지만,이 미친 짓이야 : D
필립 Haglund

따옴표 사이에 정확히 두 문자가 있습니다. 16 진수 덤프를 게시 할 수 있습니까?
Pavel

실제로 두 개를 볼 수 있습니까? 나는 운이 없다 ... UTF-8로 문자를 인코딩하면 hexdump는 다음과 같습니다. tio.run/nexus/bash#AagAV///eHhkIC1nIDH//…
데니스

6

자바 217 215 220 219 192 바이트

골프 :

public static String b(){String s="public static boolean isPowerOfTen(long input) {\n  return\n    input == 1L",z="";for(int i=0;i++<18;){z+="0";s+="\n  || input == 1"+z+"L";}return s+";\n}";}

언 골프 드 :

  public static String a(){
    String s = "public static boolean isPowerOfTen(long input) {\n  return\n    input == 1L", z="";
    for (int i=0; i++ < 18;) {
        z += "0";
        s += "\n  || input == 1"+z+"L";
    }
    return s + ";\n}";
  }

(첫 답변, wuhu)

감사!
-2 바이트 : user902383
-1 바이트 : Denham Coote

변경 사항 :

  • 공백 대신 탭 사용
  • 마지막 출력 줄을 놓쳤다 : 18-> 19
  • 내부 루프 제거
  • 인쇄에서 문자열 반환으로 변경

4
내부 for 루프는 괄호가 필요 없습니다
user902383

Java 8 구문을 사용하고 다른 것들도 ()->{String s="public static boolean isPowerOfTen(long input) {\n\treturn input == 1L";for(int i=0,k;i++<18;){s+="\n\t|| input == 1";for(k=0;k++<i;)s+="0";s+="L";}return s+";\n}";}줄였습니다 . (180 바이트) 이제 인쇄 대신 문자열을 반환하지만 짧습니다.
애디슨 크럼

1
더 자세한 Java 프로그램을 생성하기 위해 자세한 Java 프로그램을 작성하려면 +1하십시오.
Cyoce

대신 바이트를 절약 for(int i=1;i<19;i++)할 수 있습니다for(int i=1;i++<19;)
Denham Coote

또한, 선언 int i=1,k;그리고 당신은 쓸 수 for(;i++<19;)for(k=0;k++<i;)
덴햄 Coote

5

PowerShell, 120 바이트

'public static boolean isPowerOfTen(long input) {'
'  return'
"   $((0..18|%{" input == 1"+"0"*$_})-join"L`n  ||")L;`n}"

처음 두 줄은 단순히 문자열 리터럴이며 그대로 출력됩니다.

세 번째 줄은 세 개의 공백으로 시작 L;`n}"하여 마지막 몇 바이트를 끝내기 위해 끝 납니다 . 스크립트 블록 내부의 중간 비트 $(...)에 대한 루핑에 의해 구성된다 %에서 018과 문자열을 구성하는 각 반복과 함께 개시 input == 1제로의 해당 번호와 연결. 이것은 문자열 배열을 뱉어냅니다. 그런 다음 -join배열의 각 요소 L`n ||는 개행 파이프를 달성합니다. 이 큰 문자열은 스크립트 블록의 출력으로, 중간에 자동으로 삽입되어 출력됩니다.

PS C:\Tools\Scripts\golfing> .\go-generate-some-java.ps1
public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

오래 전 ... :) 매우 인상적!
mazzy

4

Pyth, 118 (106) 103 바이트

s[."
{Z-L¡JxÙÿ
LæÝ<­í?¢µb'¥ÜA«Ç}h¹äÚÏß"\nb*4dj"\n  || "ms[." uøs|ÀiÝ"*d\0\L)U19\;b\}

온라인으로 사용해보십시오!

이 모든 문자열 하드 코딩은 실제로 많은 바이트를 소비 하지만 그것에 대해 할 수있는 일은 없습니다. .

업데이트 : 압축 문자열을 사용하여 3 바이트를 절약했습니다. 힌트를 주신 @ user81655에게 감사합니다!


압축 된 문자열을 사용할 수 있습니다.
user81655

나는 Pyth를 모르고 전체 문자열을 포장하는 방법이 있는지 확실하지 않지만 (패킹 프로그램은 항상 그것을 바꿀 것입니다) 결과를 이것으로 압축하고 r연결합니다 (98 바이트). n
user81655

@ user81655 감사합니다. Pyth가이 사실을 몰랐습니다. :) 첫 번째 큰 문자열을 포장하는 것이 합리적입니다. 양식 포장 풀기의 오버 헤드는 작은 문자열에 가치가 없습니다.
Denker

@ user81655 나는 그것을 알고 있지만 103 문자를 셉니다. 어떻게 97에 도착 했습니까?
Denker

죄송합니다. 실수로 잘못 세고있었습니다.
user81655

4

C 번호 (CSI) 181 180 179 바이트

string i=" input == 1",e="public static bool";Console.Write(e+@"ean isPowerOfTen(long input) {
  return
   "+i+string.Join(@"L
  ||"+i,e.Select((_,x)=>new string('0',x)))+@"L;
}")

하나의 작은 트릭이 관련되어 있습니다. 이것을 작성하는 간단한 방법은 다음과 같습니다.

string.Join("L\n  || input == 1",Enumerable.Range(0,18).Select(x=>new string('0',x)))

어쨌든 필요한 텍스트의 첫 18 문자와 함께 문자열을 사용하면 긴 Enumerable.Range를 제거 할 수 있습니다. 이것은 문자열이 IEnumerable을 구현하고 항목 (필요하지 않음)과 람다 함수에 원하는 색인을 제공하는 Select 버전이 있기 때문에 작동합니다.


1
@WashingtonGuedes 감사
raggy

1
설명을 추가하십시오
Eumel

1
CSI는 표현 체를 지원합니까? 그렇다면,이 { return ... }로 대체 될 수있다 =>....
mınxomaτ

현재 컴퓨터에 없으므로 테스트 할 수 없습니다. 마지막 그대로의 문자열이 그 안에있는 대괄호를 이스케이프합니까? 아니면 내가 몰랐던 훌륭한 트릭입니까? :)
Yytsi

3

자바 스크립트, 172 157 152 150 148 바이트

p=>`public static boolean isPowerOfTen(long input) {
  return${[...Array(19)].map((x,i)=>`
  ${i?'||':' '} input == 1${'0'.repeat(i)}L`).join``};
}`


2
ES7에서는 ${10**i}대신을 사용하여 9 바이트를 절약 할 수 있습니다 1${'0'.repeat(i)}.
Neil

3

C, 158155 바이트

i;main(){for(puts("public static boolean isPowerOfTen(long input) {\n  return");i<19;)printf("  %s input == 1%0.*dL%s\n",i++?"||":" ",i,0,i<18?"":";\n}");}

여기에서 온라인으로 사용해보십시오 .


printf의 반환 값을 사용하면 바이트를 줄일 수 있습니다.i;main(){for(puts("public static boolean isPowerOfTen(long input) {\n return");printf(" %s input == 1%0.*dL%s\n",i++?"||":" ",i,0,i<18?"":";\n}")-37);}
algmyr

3

젤리, 75 바이트

(이것들은 Jelly의 사용자 정의 코드 페이지 의 바이트입니다 .)

0r18⁵*;@€⁶j“¢œḤḅg^NrÞḢ⁷ẉ»“⁵®UẆƓḃÐL⁴ṖịṛFþẈ¹9}¶ ƁḋȮ¦sẒẆd€Ḟɼ¿ỌṀP^µ\f@»;;“L;¶}”

여기에서 시도하십시오.

설명

0r18      Range [0..18]
⁵*        Take the 10^ of each number
;@€⁶      Prepend a space to each number
j“...»    Join by compressed string "L\n  || input =="
“...»;    Prepend compressed string "public static ... =="
;“L;¶}”   Append "L;\n}"

3

Vimscript, 120 바이트

작업에 적합한 도구를 사용할 수도 있습니다.

이것은 자동 들여 쓰기 등이 설정되지 않은 것으로 가정합니다. ^[^M에 대한 이스케이프 문자가 ESCCR 각각 문자.

a매크로는 현재 행을 복제 및 복사에 0을 추가합니다. 이 :norm라인은 모든 상용구 및 indent == 1L라인 a을 생성 한 후 다른 보일러 플레이트 를 생성하는 데 사용 됩니다.

:let @a='yyp$i0^['
:norm ipublic static boolean isPowerOfTen(long input) {^M  return^M  || input == 1L^[18@a$a;^M}
:3s/||/ /

샘플 출력의 두 줄에있는 후행 공백이 오타가 아닌 경우 여기에 포함 된 126 바이트 버전이 있습니다.

:let @a='yyp/L^Mi0^['
:norm ipublic static boolean isPowerOfTen(long input) {^M  return ^M  || input == 1L^[18@a$a;^M}   
:3s/||/ /

2

Oracle SQL 9.2, 311 바이트

SELECT REPLACE(REPLACE('public static boolean isPowerOfTen(long input) {'||CHR(10)||'  return'||c||';'||'}', 'n  ||', 'n'||CHR(10)||'   '),CHR(10)||';', ';'||CHR(10)) FROM(SELECT LEVEL l,SYS_CONNECT_BY_PATH('input == '||TO_CHAR(POWER(10,LEVEL-1))||'L'||CHR(10),'  || ')c FROM DUAL CONNECT BY LEVEL<20)WHERE l=19

2

펄 5 - 130 141

@s=map{'input == 1'.0 x$_."L\n  ||"}0..18;$s[$#s]=~s/\n  \|\|/;\n}/g;print"public static boolean isPowerOfTen(long input){\n  return\n    @s"

편집 : 정확한 들여 쓰기가되도록 수정되었습니다.


범위 주위에 괄호를 사용할 필요가 없습니다. 정확한 들여 쓰기를 재현하는 것이 좋을 것입니다.
manatwork

잊어 버린 괄호에 감사드립니다. 정확한 들여 쓰기를 위해 수정했습니다.
ChatterOne

g대체를위한 플래그 가 필요하지 않습니다 . 또한 \n해당 문자열에 단일 이 있으면 간단하게 문자열과 그 이후의 모든 항목을 일치시킬 수 있습니다 $s[$#s]=~s/\n.+/;\n}/. 그러나 join: 기반으로 한 여전히 짧은 것 pastebin.com/hQ61Adt8
manatwork

고맙지 만 솔루션을 복사하여 붙여 넣으면 좋을 것이라고 생각하지 않으므로 최선의 노력으로 그대로 두겠습니다. 시간이
흐르면

2

ES6, 139 바이트

_=>"0".repeat(19).replace(/./g,`
 || input == 1$\`L`).replace(`
 ||`,`public static boolean isPowerOfTen(long input) {
  return\n  `)+`;
}`

나는이 삼각형 생성 질문을 좋아합니다.


2

코 틀린, 194 193 자

fun main(u:Array<String>){var o="public static boolean isPowerOfTen(long input) {\n\treturn"
var p:Long=1
for(k in 0..18){
o+="\n\t"
if(k>0)o+="||"
o+=" input == ${p}L"
p*=10
}
print("$o;\n}")}

http://try.kotlinlang.org/ 에서 테스트하십시오.


프로그래밍 퍼즐 및 코드 골프에 오신 것을 환영합니다. 좋은 첫 번째 대답이지만 온라인 통역사에 대한 링크를 추가 하거나이 프로그램을 실행하는 방법에 대한 예를 추가하여 다른 사람들이 확인할 수 있도록하십시오. 그러나 좋은 시간 보내세요! :)
Denker

2

루비, 125 119 바이트

$><<'public static boolean isPowerOfTen(long input) {
  return
   '+(0..19).map{|i|" input == #{10**i}L"}*'
  ||'+';
}'

-6 바이트의 manatwork 덕분에 !


많은 원래 아니 솔루션의 대부분은 이런 식으로 일을 같이하지만, 여전히 짧은 : pastebin.com/1ZGF0QTs
manatwork

2

jq, 123 자

(121 자 코드 + 2 자 명령 행 옵션)

"public static boolean isPowerOfTen(long input) {
  return
   \([range(19)|" input == 1\("0"*.//"")L"]|join("
  ||"));
}"

샘플 실행 :

bash-4.3$ jq -nr '"public static boolean isPowerOfTen(long input) {
>   return
>    \([range(19)|" input == 1\("0"*.//"")L"]|join("
>   ||"));
> }"'
public static boolean isPowerOfTen(long input) {
  return
    input == 1L
  || input == 10L
  || input == 100L
  || input == 1000L
  || input == 10000L
  || input == 100000L
  || input == 1000000L
  || input == 10000000L
  || input == 100000000L
  || input == 1000000000L
  || input == 10000000000L
  || input == 100000000000L
  || input == 1000000000000L
  || input == 10000000000000L
  || input == 100000000000000L
  || input == 1000000000000000L
  || input == 10000000000000000L
  || input == 100000000000000000L
  || input == 1000000000000000000L;
}

온라인 테스트 ( -rURL을 통한 전달 은 지원되지 않습니다. 직접 Raw 출력을 확인하십시오.)


1

자바 스크립트 175 바이트

이것을 정기적으로하자

var s = "public static boolean isPowerOfTen(long input) {\n\treturn\n\t\tinput == 1";
for (var i = 1; i < 20; i++) {
    s += "\n\t|| input == 1";
    for (var j = 0; j < i; j++) {
        s += "0";
    }
    s += "L" ;
}
s += ";\n}";
alert(s);

꽤 작습니다. 이제 세미콜론이 필요 없거나 var가없는 것과 같은 자바 스크립트 마술이 있습니다.

k="input == 1"
s="public static boolean isPowerOfTen(long input) {\n\treturn\n\t\t"+k+"L"
for(i=1;i<20;i++){s+="\n\t|| "+k
for(j=0;j<i;j++)s+="0";s+="L"}s+=";\n}"
alert(s)

마법이 어떻게 작동 하는지 설명 할 수 있습니까 ? :)
Marv

3
Javascript는 키워드 (for, while, var 등)가 다른 것을 "만지지"않을 때까지 세미콜론에 신경 쓰지 않습니다. 또한 var 키워드를 사용하지 않으면 전역 변수가 생깁니다. 지금까지 프로그래밍 언어에서 본 것 중 최악의 기능입니다.
Bálint

@ 발린 이것이 왜 최악의 기능 일까요?
제거

@WashingtonGuedes 아시다시피, 대부분의 언어는 함수 내부에서 무언가를 잘못 입력했을 때 상기시켜줍니다. 자바 스크립트는 완전히 새로운 변수를 만든 것처럼 그것을 취하기 때문에 그것에 대해 아무 말도하지 않습니다.
Bálint

또한 동일한 것이 = true 반환에 적용됩니다.
Bálint

1

파이썬 (3.5) 137136 바이트

print("public static boolean isPowerOfTen(long input) {\n  return\n   ",'\n  || '.join("input == %rL"%10**i for i in range(19))+";\n}")

이전 버전

print("public static boolean isPowerOfTen(long input) {\n  return\n   ",'\n  || '.join("input == 1"+"0"*i+"L"for i in range(19))+";\n}")

135 Python 2.7 :print "public static boolean isPowerOfTen(long input) {\n return\n %s;\n}"%"\n || ".join("input == %r"%10L**i for i in range(19))
moooeeeep

@moooeeeep 당신이 옳습니다, % r을 사용하면 1 바이트를 얻고 python 2 print(괄호없이)는 또 하나를 얻습니다
Erwan

0

ANSI-SQL, 252 자

WITH t as(SELECT '   'x,1 c,1 l UNION SELECT'  ||',c*10,l+1 FROM t WHERE l<19)SELECT 'public static boolean isPowerOfTen(long input) {'UNION ALL SELECT'  return 'UNION ALL SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19)FROM t UNION ALL SELECT'}   ';

언 골프 드 :

WITH t as (SELECT '   ' x,1 c,1 l UNION
           SELECT '  ||',c*10,l+1 FROM t WHERE l<19)
SELECT 'public static boolean isPowerOfTen(long input) {' UNION ALL
SELECT '  return ' UNION ALL
SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19) FROM t UNION ALL
SELECT '}   ';

심각한 시도는 아니지만 Oracle SQL / T-SQL 항목을 파킹하기 만하면됩니다.


40 개의 추가 문자를 위해 "dual"을 추가하여 "Oracle SQL"항목으로 만들 수 있습니다.
user1361991

0

자바 스크립트 (Node.js), 156 바이트

s="public static boolean isPowerOfTen(long input) {\n  return "
for(i=1;i<1e19;i*=10)s+="\n  "+(i-1?"||":" ")+" input == "+i+"L"
console.log(s+";\n}   \n")

(가) i-1단지 첫 라운드 (falsey 따라서) 0이 될 것이다 (그것은보다 단지 약간 짧다i!=1.

제안을 환영합니다!


0

Perl 5, 137 bytes

Not based on the previous Perl answer, but it is somehow shorter. I believe it can be shortened down again by taking care of the first "input" inside the loop, but I didn't try anything yet (at work atm)

$i="input";for(1..18){$b.="  || $i == 1"."0"x$_."L;\n"}print"public static boolean isPowerOfTen(long $i) {\n  return\n    $i == 1L;\n$b}"

0

CJam, 112 chars

"public static boolean isPowerOfTen(long input) {
  return
    input == 1"19,"0"a19*.*"L
  || input == 1"*"L;
}"

0

AWK+shell, 157 bytes

echo 18|awk '{s="input == 1";printf"public static boolean isPowerOfTen(long input) {\n return\n    "s"L";for(;I<$1;I++)printf"\n  ||%sL",s=s"0";print";\n}"}'

The question did say to count everything you would have to type. This does have the added bonus of being able to select how many lines would be placed in the isPowersOfTen method when the boss inevitably changes his mind.


Passing a here-string is shorter than piping from echo: awk '…'<<<18
manatwork

I knew about here-file but not here-string. Thanks for the info.
Robert Benson

0

T-SQL 289, 277, 250, 249 bytes

SELECT'public static boolean isPowerOfTen(long input){return '+STUFF((SELECT'||input=='+N+'L 'FROM(SELECT TOP 19 FORMAT(POWER(10.0,ROW_NUMBER()OVER(ORDER BY id)),'F0')N FROM syscolumns)A FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'),1,2,'')+';}'

Update: Thanks @Bridge, I found a few more spaces too :)

Update2: Changed CTE to subquery -27 chars :) Update3: Another space bites the dust @bridge :)


1
I was able to trim off 7 more spaces (282 bytes) without changing the rest of the code: WITH A AS(SELECT CAST('1'AS VARCHAR(20))N UNION ALL SELECT CAST(CONCAT(N,'0')AS VARCHAR(20))FROM A WHERE LEN(N)<20)SELECT'public static boolean isPowerOfTen(long input){return '+STUFF((SELECT'|| input=='+N+'L 'FROM A FOR XML PATH(''),TYPE).value('.', 'VARCHAR(MAX)'), 1, 3, '')+';}'
Bridge

1
Now I look back I can see all the extra spaces in my original comment! I've found one more space you can get rid of - the one immediately after ROW_NUMBER()
Bridge

0

R, 185 bytes

Golfed

options(scipen=999);p=paste;cat(p("public static boolean isPowerOfTen(long input) {"," return",p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"),"}",sep="\n"))

Ungolfed

options(scipen=999)
p=paste
cat(
  p("public static boolean isPowerOfTen(long input) {",
        " return",
        p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"),
        "}",
        sep="\n")
)

0

Perl 6 (115 bytes)

say "public static boolean isPowerOfTen(long input) \{
  return
   {join "L
  ||",(" input == "X~(10 X**^19))}L;
}"

X operator does list cartesian product operation, for example 10 X** ^19 gives powers of ten (from 10 to the power of 0 to 19, as ^ is a range operator that counts from 0). Strings can have code blocks with { (which is why I escape the first instance of it).


0

Java, 210 / 166

Score is depending on whether returning the input from a function meets the definition of 'output'.

Console output (210):

class A{public static void main(String[]z){String a=" input == 1",t="L\n  ||"+a,s="public static boolean isPowerOfTen(long input) {\n  return\n   "+a;for(int i=0;++i<19;)s+=t+="0";System.out.print(s+"L;\n}");}}

String return (166):

String a(){String a=" input == 1",t="L\n  ||"+a,s="public static boolean isPowerOfTen(long input) {\n  return\n   "+a;for(int i=0;++i<19;)s+=t+="0";return s+"L;\n}";}

Legible version:

String a() {
    String a=" input == 1", t = "L\n  ||"+a,
        s = "public static boolean isPowerOfTen(long input) {\n  return\n   "+a;
    for (int i = 0; ++i < 19;)
        s += t += "0";
    return s + "L;\n}";
}

0

Batch, 230 208 206 205 bytes

@echo off
echo public static boolean isPowerOfTen(long input) {
echo   return
set m=input == 1
echo    %m%L
for /l %%a in (1,1,17)do call:a
call:a ;
echo }
exit/b
:a
set m=%m%0
echo  ^|^| %m%L%1

Edit: Saved 22 bytes by avoiding repeating input == and reusing the subroutine for the line with the extra semicolon. Saved 2 3 bytes by removing unnecessary spaces.


Do you need spaces around ==?
Pavel

@Pavel That's not code; it's part of the output.
Dennis
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.