Home > OS >  How to return colon in int method? (C#)
How to return colon in int method? (C#)

Time:05-24

in coderbyte it says return numbers as hour:minute but in integer method. How can I return numbers with colon as time in c#?

    using System;

class MainClass {

  public static int StringChallenge(int num) {

    // code goes here  
    int hour=0;
    int min ;
    if (num<60)
    {
      
      min = num;
       }
    if (num>60)
    {
      min = num % 60;
      hour = num / 60;
     
    }

    return "hour:min"??? ;

  }

  static void Main() {  
    // keep this function call here
    Console.WriteLine(StringChallenge(Console.ReadLine()));
  } 

}

CodePudding user response:

Let TimeSpan do the work for you:

int num = 60;
TimeSpan ts = TimeSpan.FromMinutes(num);
string formatted = ts.ToString(@"hh\:mm");

which outputs a string like

01:00

To change the format, different patterns can be used. Check out the documentation on this if necessary.

CodePudding user response:

Here I have taken the method:

public static string StringChallenge(int minute)
{
    return $"{minute / 60}:{minute % 60}";
}

from a 59 turns into "0:59"

from a 60 turns into "1:0"

from a 61 turns into"1:1"

CodePudding user response:

In general case, I can see two problems here:

  • Large num, say num = 1600, we want 26:40, not 1 day 2:40
  • Negative numbers: we want -12:30, not -12:30

Code

// Note, that we should return string, not int
// d2 - formatting - to have leading zeroes, i.e. 5:01 instead of 5:1
public static string StringChallenge(int num) =>
  $"{num / 60}:{Math.Abs(num % 60):d2}";

CodePudding user response:

Use string interpolation

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

using System;

class MainClass {

  public static string StringChallenge(int num) {
    Console.WriteLine(num);
    // code goes here  
    int hour=0;
    int min=0 ;
    if (num<60)
    {
      
      min = num;
       }
    if (num>60)
    {
      min = num % 60;
      hour = num / 60;
     
    }

    return $"{hour} : {min}";

  }

  static void Main() {  
    // keep this function call here
    Console.WriteLine(StringChallenge(int.Parse(Console.ReadLine())));
  } 

}
  •  Tags:  
  • c#
  • Related