How to check is a number is on left side or right side of number
for example number is 2 and i want where it is on 12 and 23
which is 2 is left side on 23 and right side on 12
my code
class Solution
{
public static void Main(String[] args)
{
var number = 12;
foreach(char c in number.ToString()){
if(c=='2'){
Console.WriteLine(c);
}
}
}
}
CodePudding user response:
class Solution
{
public static void Main(String[] args)
{
bool isLeft = true;
var number = 12;
foreach(char c in number.ToString()){
if(c=='2'){
if(isLeft)
{
Console.WriteLine("It's on the left.");
}
else
{
Console.WriteLine("It's on the right");
}
Console.WriteLine(c);
}
isLeft = false;
}
}
}
EDIT: I added proof
class Program
{
static void Main(string[] args)
{
NewMethod(12);
NewMethod(23);
}
private static void NewMethod(int number)
{
bool isLeft = true;
foreach (char c in number.ToString())
{
if (c == '2')
{
if (isLeft)
{
Console.WriteLine("It's on the left.");
}
else
{
Console.WriteLine("It's on the right");
}
Console.WriteLine(c);
}
isLeft = false;
}
}
}
Proof un-edited version works:
CodePudding user response:
Check this code out:
CheckNumber(12);
CheckNumber(23);
static void CheckNumber(int number)
{
var str = number.ToString();
if (str[0] == '2')
Console.WriteLine("2 is in left");
if (str[^1] == '2')
Console.WriteLine("2 is in right");
}