How do I do this in Java, C#, or Python?

148 views Asked by At

I was given a code challenge that I failed on (rather badly) for a junior dev job and its been going through my mind over and over.

The question was: assume N is of length 1-100. The task is to return N as a string.

For example if N = 5 then return "+-+-+" or if N is 3 then retun "+-+"

N was assigned to type Int at the start of the algorithm.

I tried using Java but failing the test I don't see how showing my code will help. All im after is a solution so I can see how it is done and learn from it.

I may use the following languages: Java, Python, C#.

5

There are 5 answers

2
qqqqqqq On
using System;
using System.Text;

public class Program
{
    private static string StringN(int N)
    {
        var builder = new StringBuilder();
        for(int i = 0; i < N; ++i)
        {
            builder.Append(i%2 == 0 ? "+" : "-");
        }
        return builder.ToString();
    }

    public static void Main()
    {
        for(int i = 0; i < 10; ++i)
        {
            Console.WriteLine(StringN(i));
        }
    }
}

Here is a fiddle. C# is used in the above code.

1
Matthew On
n = int(input("Enter N:"))

for i in range(0,n):
    if i % 2 == 0:
        print("+", end =""),
    else:
        print("-",  end =""),

Here is a solution in python

0
Tim Hunter On

A (non-condensed) version in Java:

  public static void main(String[] args) {
    Random rand = new Random();
    int N = rand.nextInt(100) + 1;
    StringBuilder builder = new StringBuilder();

    for(int i = 0; i < N; i++) {
      if(i % 2 == 0)
        builder.append("+");
      else
        builder.append("-");
    }

    System.out.println("Value: " + N);
    System.out.println(builder.toString());
  }
2
HomeIsWhereThePcIs On

Java 11+

public static String getStringFromN(int n) {
    return String.format("%s%s", "+-".repeat(n / 2), n % 2 == 1 ? "+" : "");
}
2
Pedro Rodrigues On

Multiply the string +- n times. Return the first n characters from that string.

In Python

>>> def f(n):
...     template = '+-'
...     string = template * n
...     return string[:n]
... 
>>> f(5)
'+-+-+'
>>> f(3)
'+-+'
>>> 

Or, in one line f = lambda n: ('+-' * n)[:n].

In C Sharp

using System;
using System.Text;

public class Program
{
    private static string f(int n)
    {
        var builder = new StringBuilder();

        for(int i = 0; i < n; i++)
            builder.Append("+-");

        return builder.ToString().Substring(n);
    }

    public static void Main()
    {
        Console.WriteLine(f(3));
        Console.WriteLine(f(5));
    }
}

And a fiddle.