Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Your boss wants you to write code like this:

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, at http://codereview.stackexchange.com/a/117294/61929)

which is efficient and so, but not that fun to type. Since you want to minimize the number of keypresses you have to do, you write a shorter program or function (or method) that outputs this function for you. And since you have your very own custom full-range unicode keyboard with all 120,737 keys required for all of unicode 8.0, we count unicode characters, instead of keypresses. Or bytes, if your language doesn't use unicode source code.

Any input your program or function takes counts towards your score, since you obviously have to type that in as well.

share|improve this question
7  
0==Math.log10(input)%1 – SuperJedi224 15 hours ago
5  
You say "we count unicode characters," but then you immediately say "Or bytes." Which one is it? – Doorknob 14 hours ago
    
Whichever you prefer, i.e. the one that gives you the lowest score. Added bytes to allow languages that don't use text source. – Filip Haglund 13 hours ago
1  
while(input%10==0) input/=10; return input == 1; – PSkocik 11 hours ago
1  
05AB1E uses windows CP1252, which is bytes, not unicode. I'm aiming for standard rules, but I get told I'm wrong all the time. – Filip Haglund 6 hours ago

20 Answers 20

PostgreSQL, 158 characters

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

05AB1E, 99 97 96 94 93 bytes

Code:

“‚Æ£‹ÒŒ€ˆPowerOfTen(“ ?“¢„î®) {“ ,“ «‡
   “ ?19FN0›i"  ||"?}’ î® == ’ ?N°?'L?N18Qi';,"}"?}"",

Uses CP-1252 encoding.

share|improve this answer

Java, 217 215 bytes

Golfed:

public static void a(){String s="public static boolean isPowerOfTen(long input) {\n\treturn input == 1L";for(int i=1;i<18;i++){s+="\n\t|| input == 1";for(int k=0;k<i;k++)s+="0";s+="L";}System.out.println(s+";\n}");}

Ungolfed:

public static void a(){
    String s = "public static boolean isPowerOfTen(long input) {\n\treturn input == 1L";
    for (int i = 1; i < 18; i++) {
        s += "\n\t|| input == 1";
        for (int k = 0; k<i; k++)
            s += "0";
        s += "L";
    }
    System.out.println(s + ";\n}");
  }
}

(first answer, wuhu)

Thanks!
-2 bytes: user902383

share|improve this answer
4  
your inner for loop does not need brackets – user902383 9 hours ago
    
Use Java 8 syntax, also shortened some other stuff: ()->{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 bytes) Now returns the string instead of printing, but that's shorter. – VoteToClose 6 hours ago

Pyth, 118 106 103 bytes

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

Try it online!

All this string hardcoding really eats a lot of bytes up, but nothing I can do about it.

Update: Saved 3 bytes by using a packed string. Thanks @user81655 for the hint!

share|improve this answer
    
You could use packed strings... – user81655 13 hours ago
    
I don't know Pyth and I'm not sure if there's a way to pack the full string (the packing program would always alter it) but packing up to r and concatenating the n results in this (98 bytes). – user81655 13 hours ago
    
@user81655 Thanks, didn't know Pyth had this. :) It only makes sense to pack the first big string tho, the overhead you produce form unpacking is not worth it for smaller string. – DenkerAffe 12 hours ago
    
By the way, each character produced by packed strings has code points of less than 256, so assuming an encoding like CP1252 means this would be one byte-per-character, so 97 bytes in total. – user81655 5 hours ago

Ruby, 125 bytes

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

Explanation to come.

share|improve this answer
    
Not much original as most of the solutions are doing this way, but still shorter: pastebin.com/1ZGF0QTs – manatwork 9 hours ago

Oracle SQL 9.2, 311 bytes

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
share|improve this answer

Javascript, 172 157 152 150 148 bytes

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

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

document.body.innerHTML = '<pre>' + f() + '</pre>'

share|improve this answer
    
In ES7 you can save 9 bytes by using ${10**i} instead of 1${'0'.repeat(i)}. – Neil 4 hours ago

C, 158 155 bytes

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}");}

Try it online here.

share|improve this answer
    
+1! If anyone can beat this (in C)... – YoYoYonnY 8 hours ago

C# (CSI) 181 180 179 byte

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;
}")

There is only one little trick involved. The straight forward way to write this would be:

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

by using the string with the first 18 characters of the text which I need anyways I can get rid off the lengthy Enumerable.Range. This works because string implements IEnumerable and there is a version of Select that hands the item (not needed) and the index which we want to the lambda function.

share|improve this answer
1  
@WashingtonGuedes Thanks – raggy 13 hours ago
1  
add some explanation please – Eumel 12 hours ago
1  
Does CSI support expression bodies? If so, the { return ... } can be replaced by =>.... – mınxomaτ 12 hours ago

Perl 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"

EDIT: fixed to have exact indentation

share|improve this answer
    
No need to use parenthesis around the range. In change would be nice to reproduce the exact indentation. – manatwork 10 hours ago
    
Thanks for the parenthesis that I forgot. I've fixed it to have the exact indentation. – ChatterOne 10 hours ago
    
There is no need for the g flag for the substitution. Also as you have a single \n in that string, you can simply match it and everything after it: $s[$#s]=~s/\n.+/;\n}/. But a join based one would still be shorter: pastebin.com/hQ61Adt8 – manatwork 9 hours ago
    
Thank you, but I don't think it would be nice if I just copied and pasted your solution, so I'll just leave it as it is as my own best effort. In time, I'll get better at golfing :-) – ChatterOne 6 hours ago

jq, 123 characters

(121 characters code + 2 characters command line option.)

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

Sample run:

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;
}
share|improve this answer

Python (3.5) 137 bytes

print("public static boolean isPowerOfTen(long input) {\n  return\n   ",'\n  || '.join("input == 1"+"0"*i+"L"for i in range(19))+";\n}")
share|improve this answer
    
135 with 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 6 hours ago

PowerShell, 120 bytes

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

The first two lines are simply string literals, which are output as-is.

The third line starts with three spaces, and ends with L;`n}" to finish off the last couple bytes. The middle bit inside the script block $(...) is constructed by for-looping % from 0 to 18 and each iteration constructing a string that starts with input == 1 concatenated with the corresponding number of zeros. This will spit out an array of strings. We then -join each element of the array with L`n || to achieve the newline-pipes. That big string is the output of the script block, which gets inserted automatically into the middle and output.

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;
}
share|improve this answer

Jelly, 75 bytes

(These are bytes in Jelly's custom codepage.)

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

Try it here.

Explanation

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}"
share|improve this answer

T-SQL 289 bytes

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, '' )+';}'
share|improve this answer

Javascript 175 bytes

Let's do this regularly

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);

Pretty small. Now, some javascript magic, like no semicolons needed, or no var's, etc.:

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)
share|improve this answer
    
Can you explain how that magic works? :) – Marv 11 hours ago
2  
Javascript doesn't care about semicolons, at least until the keywords (for, while, var, etc.) aren't "touching" anything else. Also, if you don't use the var keyword, you get global variables, wich is the worst feature I have ever seen in a programming language thus far. – Bálint 11 hours ago
    
@Bálint. Why this would be the worst feature? – Washington Guedes 11 hours ago
    
@WashingtonGuedes You know, most languages remind you if you misstyped something inside a function. Because javascript takes that as if you made a whole new variable, it does not going to say anything about that. – Bálint 10 hours ago
    
Also, same one applies to = returning a true. – Bálint 10 hours ago

Java 215

class A{public static void main(String[]a){String s="public static boolean isPowerOfTen(long input) {\n  return\n   ";for(long i=1;i>0;i*=10)s+=" input == "+i+"L\n  ||";System.out.print(s.substring(0,515)+";\n}");}}

or if

you write a shorter program or function that outputs this function for you

can be interpreted to allow for writing a Java method that returns a String, then this can be golfed down to 171:

String a(){String s="public static boolean isPowerOfTen(long input) {\n  return\n   ";for(long i=1;i>0;i*=10)s+=" input == "+i+"L\n  ||";return s.substring(0,515)+";\n}";}
share|improve this answer

ES6, 139 bytes

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

I do so love these triangle generation questions.

share|improve this answer

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[]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";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}";
}
share|improve this answer

Haskell, 132 146 bytes

It would make no sense to ask people to write code like that and then to complain about style (i.e. spacing, indentation). So I ignored useless spaces. Both in Java and Haskell (in fact, the Haskell code itself has 0 spaces). Also with modern text editors, the leading whitespace is automatic, no one really types it.

"public static boolean isPowerOfTen(long input){return input==1L"++unlines(map((\x->"||input=="++x++"L").show.((^)10))[1..19])++"}"

No s=... because I took ghci as a shell. Use putStrLn before it to show the string itself instead of displaying (with \n). I'd try zlib to pack the initial string, but that would mean way too many imports (Data.Char, Codec.Compression.GZip, Data.ByteString.Lazy), which would likely take more space than the string itself

About the Unicode keyboard: it's cheating. Then I could have a keyboard for which every possible 4 byte combo was a key. Or even one with so many keys that one of them would type the code above. á takes 2 keystrokes, full stop.

Same thing with spacing as in the original:

public static boolean isPowerOfTen(long input){\n  return\n    input==1L\n"++unlines(map((\x->"  || input=="++x++"L").show.((^)10))[1..19])++"}"
share|improve this answer
1  
Welcome to Programming Puzzles & Code Golf! All submissions here must fully comply with the challenge specification. In this case, the leading whitespace is required for this to be a valid submission. – Alex A. 6 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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