Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

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

I'm trying to find the shortest and best way to achieve the following:

Given input integer $N, get the following output:

  • n = 0, output = 0
  • n = 1, output = 0
  • n = 2, output = 10
  • n = 3, output = 100
  • n = 4, output = 1000
  • n = 5, output = 10000

I do this with the following code, but there must be a better option to do this.

<?php

    $n = 1;

    function getNumber($n) {
        if ($n === 0 OR $n === 1) {
            return "0";
        } else {
            return "1".str_repeat("0", $n -1);
        }
    }

    echo getNumber($n);
?>
share|improve this question
3  
Just an overall comment, but calling a function 'getNumber' when it returns a string may not be the best solution to your problem – A. Romeu Mar 25 at 15:09
3  
What you may and may not do after receiving answers. I've rolled back Rev 2 → 1. – 200_success Mar 25 at 15:18
    
Allright, won't do it again! Tnx :-) – Chilion Mar 25 at 15:19
up vote 5 down vote accepted

Maybe you want something short like is

echo ($n <= 1) ? 0 : pow(10, $n - 1);
share|improve this answer

The pow function is probably what you are looking for.

return pow(10, $n-1); should be close to what you want but might need tweeking for borderline cases.

share|improve this answer

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.