ID Number Generator - c#

I keep getting an "int cannot convert to bool" error at if(number % NUMINROW), and I do not know how to fix it. I am fairly new to C#, but I know Python and how for loops work, but I am still confused.
// Program displays every possible ID number for a company
// ID number is a letter, followed by a two-digit number
// For example -- A00 or Z99
// Go to a new display line after every 20 IDs
using static System.Console;
class DebugFive3
{
static void Main()
{
char letter;
int number;
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
for(letter = 'A'; letter <= 'Z'; ++letter)
for(number = LOW; number >= HIGH; ++number)
{
if(number % NUMINROW)
WriteLine();
Write("{0}{1} ", letter, number.ToString("D2"));
}
}
}

You have error on second for and in condition if(number % NUMINROW)
static void Main(string[] args)
{
char letter;
int number;
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
for (letter = 'A'; letter <= 'Z'; ++letter)
{
for (number = LOW; number <= HIGH; ++number)
{
if (number % NUMINROW == 0)
Console.WriteLine();
else
Console.Write("{0}{1} ", letter, number.ToString("D2"));
}
}
Console.ReadLine();
}

The reason you're getting that compile error is that number % NUMINROW returns the remainder after dividing number by NUMINROW, which is an int, whereas an if condition must return a bool (and there is no implicit conversion from int to bool in C#).
One way to fix this is to modify the condition so that it compares the result of the modulus operation to another int, for example:
if(number % NUMINROW == 0)
Other Issues
There is no Console.ReadLine() at the end of the Main method, so as soon as the data is displayed, the console window will dissapear. Adding this line will pause execution until the user presses the Enter key, giving them time to see the data.
This condition is incorrect: number = LOW; number >= HIGH. It reads, "set number to LOW, then loop while number is greater than or equal to HIGH." That condition will never be true!! We should use <= instead.
The current code is completely ignoring the 20th column. To solve this, we can remove the else clause and switch the order of the code lines so that we always write the value, and then conditionally add a new line.
Assuming we want NUMINROW columns displayed, our modulus condition should compare the next number to this value, since we're starting at 0 (so the first row would be 0-19, followed by 20-39). Another reason to add one to the value before doing the comparison is that 0 modulus any number is 0, so we would have an extra new line before the first item (where number is 0).
Not a problem, really, but since we don't use the variables letter or number outside the loops, it's generally better to declare them as part of the for loop itself, to reduce their scope.
Here's a sample of how to solve these issues:
static void Main(string[] args)
{
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
for (char letter = 'A'; letter <= 'Z'; letter++)
{
for (int number = LOW; number <= HIGH; number++)
{
Write("{0}{1} ", letter, number.ToString("D2"));
if ((number + 1) % NUMINROW == 0) WriteLine();
}
}
ReadLine(); // Wait for user input
}
Output
As a side note, here's a fun little sample using System.Linq that does it all in one line (not recommended, since it's hard to read/debug, but thought it might be interesting):
const int LOW = 0;
const int HIGH = 99;
const int NUMINROW = 20;
WriteLine(string.Concat(Enumerable.Range('A', 26)
.Select(chr => string.Concat(Enumerable.Range(LOW, HIGH + 1)
.Select(num => $"{(char) chr}{num:D2}" + ((num + 1) % NUMINROW == 0
? Environment.NewLine : " "))))));
ReadLine();

Related

Reassigning a value to a character array not working

I am currently having issues reassigning a value to a character array. Below is my code (unfinished solution to find the next smallest palindrome):
public int nextSmallestPalindrome(int number)
{
string numberString = number.ToString();
// Case 1: Palindrome is all 9s
for (int i = 0; i < numberString.Length; i++)
{
if (numberString[i] != '9')
{
break;
}
int result = number + 2;
return result;
}
// Case 2: Is a palindrome
int high = numberString.Length - 1;
int low = 0;
bool isPalindrome = true;
for (low = 0; low <= high; low++, high--)
{
if (numberString[low] != numberString[high])
{
isPalindrome = false;
break;
}
}
char[] array = numberString.ToCharArray();
if (isPalindrome == true)
{
// While the middle character is 9
while (numberString[high] == '9' || numberString[low] == '9')
{
array[high] = '0';
array[low] = '0';
high++;
low--;
}
int replacedvalue1 = (int)Char.GetNumericValue(numberString[high]) + 1;
int replacedvalue2 = (int)Char.GetNumericValue(numberString[low]) + 1;
StringBuilder result = new StringBuilder(new string(array));
if (high == low)
{
result[high] = (char)replacedvalue1;
}
else
{
Console.WriteLine(result.ToString());
result[high] = (char)replacedvalue1;
Console.WriteLine(result.ToString());
result[low] = (char)replacedvalue2;
}
return Int32.Parse(result.ToString());
}
else return -1;
}
Main class runs:
Console.WriteLine(nextSmallestPalindrome(1001));
This returns 1001, then 101 and then gives a formatexception at the return Int32.Parse(result.ToString()); statement.
I am very confused, as I believe "result" should be 1101 after I assign result[high] = (char)replacedvalue1;. Printing replacedvalue1 gives me "1" as expected. However, debugging it line by line shows that "1001" turns into "1 1" at the end, signifying strange characters.
What could be going wrong?
Thanks
Characters and numbers aren't the same thing. I find it easiest to keep an ASCII chart open when doing this sort of thing.
If you look at one of those charts, you'll see that the character 0 actually has a decimal value of 48.
char c = (char)48; // Equals the character '0'
The reverse is also true:
char c = '0';
int i = (int)c; // Equals the number 48
You managed to keep chars and ints separate for the most part, but at the end you got them mixed up:
// Char.GetNumericValue('0') will return the number 0
// so now replacedvalue1 will equal 1
int replacedvalue1 = (int)Char.GetNumericValue(numberString[high]) + 1;
// You are casting the number 1 to a character, which according to the
// ASCII chart is the (unprintable) character SOH (start of heading)
result[high] = (char)replacedvalue1;
FYI you don't actually need to cast a char back-and-forth in order to perform operations on it. char c = 'a'; c++; is valid, and will equal the next character on the table ('b'). Similarly you can increment numeric characters:
char c = '0'; c++; // c now equals '1'
Edit: The easiest way to turn an integer 1 into the character '1' is to "add" the integer to the character '0':
result[high] = (char)('0' + replacedvalue1);
Of course there are much easier ways to accomplish what you are trying to do, but these techniques (converting and adding chars and ints) are good tools to know.
You do not have write that much code to do it.
Here is your IsPalindrome method;
private static bool IsPalindrome(int n)
{
string ns = n.ToString(CultureInfo.InvariantCulture);
var reversed = string.Join("", ns.Reverse());
return (ns == reversed);
}
private static int FindTheNextSmallestPalindrome(int x)
{
for (int i = x; i < 2147483647; i++)
{
if (IsPalindrome(i))
{
return i;
}
}
throw new Exception("Number must be less than 2147483647");
}
This is how you call it. You do not need an array to call it. You can just enter any number which is less than 2147483647(max value of int) and get the next palindrome value.
var mynumbers = new[] {10, 101, 120, 110, 1001};
foreach (var mynumber in mynumbers)
{
Console.WriteLine(FindTheNextPalindrome(mynumber));
}

C# Code Verification Program

Alright so I am making a program to verify a 4 digit code.
The computer generates a 4 digit code
The user types in a 4 digit code. Their guess.
the computer tells them how many digits are
guessed correctly in the correct place and how many digits have
been guessed correctly but in the wrong place.
The user gets 12 guesses to either win – guess the right code. Or
lose – run out of guesses.
So basically, my program doesn't seem to actually verify whether the code is correct but i cant see why not because i have if and for loops for verification, please take a look.
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int DigitOne = random.Next(0, 10);
int DigitTwo = random.Next(0, 10);
int DigitThree = random.Next(0, 10);
int DigitFour = random.Next(0, 10);
byte[] code = new byte[4];
code[0] = Convert.ToByte(DigitOne);
code[1] = Convert.ToByte(DigitTwo);
code[2] = Convert.ToByte(DigitThree);
code[3] = Convert.ToByte(DigitFour);
bool CodeCorrect = false;
Console.WriteLine(code[0] +""+ code[1] +""+ code[2]+""+code [3] );
Console.WriteLine("You have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while (AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
for (int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(Console.Read()) - 48;
}
if (UserCode.Length != 4)
{
Console.WriteLine("Error. Try Again.\n");
}
else
{
int UserDigitOne = UserCode[0];
int UserDigitTwo = UserCode[1];
int UserDigitThree = UserCode[2];
int UserDigitFour = UserCode[3];
for (int i = 0; i < 4; i++)
{
if (UserCode[i] == code[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
}
}
if (UserCode[0] == code[0] && UserCode[1] == code[1] && UserCode[2] == code[2] && UserCode[3] == code[3])
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if (AmountOfGuesses > 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
If you step through the code after it generated the number 1246, and then input the same number from the command line, convert it to a char array, then convert each char to a byte, you'll get the following four bytes:
49 50 52 54
These correspond to the ASCII representations of each char, NOT the actual numbers.
Try something like this:
int[] input = new int[4];
for(int i = 0; i < 4; i++ )
{
input[i] = Convert.ToInt32(Console.Read()) - 48;
}
The -48 should turn your ASCII code into the actual numerical representation that was provided. Console.Read() reads individual characters rather than the full line.
Also, you don't have to say:
CodeCorrect == false
This is more simply represented as:
!CodeCorrect
Similarly, if it was set to true, it would just be:
CodeCorrect
I also suggest using a for loop to set multiple elements in an array rather than manually writing out each line of code. It's not a big deal for small arrays, but it's good practice.
UPDATE: Here's a revised version of the full program:
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int[] randCombination = new int[4];
for (int i = 0; i < 4; i++)
{
randCombination[i] = random.Next(0, 10);
Console.Write(randCombination[i].ToString());
}
bool CodeCorrect = false;
Console.WriteLine("\nYou have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while(AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
string input = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(input, out n);
int correctCount = 0;
if(input.Length != 4 || !isNumeric)
{
Console.WriteLine("Error. Input code was not a 4 digit number.\n");
}
else
{
for(int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(input[i]) - 48;
if(UserCode[i] == randCombination[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
correctCount++;
}
}
if(correctCount == 4)
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if(AmountOfGuesses >= 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
}
A couple of things were changed:
Added a for loop at the top that generates a random number, enters it into an array of ints and then prints it to standard output.
I changed the way user input is read back to the Console.ReadLine(). The reason for this is to check if the user inputted a four digit integer. the int.TryParse statement makes sure the input is an int, and the Length property checks the length.
I also used a counter to count each correct guess. If 4 correct digit guesses were made, the safe is unlocked.
Your final if statement would never have evaluated because Amount of Guesses would equal 12, not be greater than it. Changed it to >= from >. Always be on the lookout for small things like this.
EDIT #2: For more information on int.TryParse, see the following:
http://www.dotnetperls.com/int-tryparse
How the int.TryParse actually works
You are comparing numbers with the character representation of a number. Each value of code[] represents an actual number. You then compare those values with the values in UserCode which is a string, meaning there is a character at each index. It is never the case that ((byte)'4') == ((byte)4) (using 4 as an example, but works for any numerical digit).
One way around this is to parse each user input character into a byte using the byte.Parse method.
For fun learning purposes look at the output from the following code:
for (char i = '0'; i <= '9'; i++)
{
Console.WriteLine("char: " + i + "; value: " + ((byte)i));
}
The output is actually:
char: 0; value: 48
char: 1; value: 49
char: 2; value: 50
char: 3; value: 51
char: 4; value: 52
char: 5; value: 53
char: 6; value: 54
char: 7; value: 55
char: 8; value: 56
char: 9; value: 57
This is due to string encoding.
I would also recommend that one you have your code working that you submit it to the fine folks at the Code Review site to review other aspects of the code which could use work.

C# equivalent to Java's scn.nextInt( )

In Java, if we want to read an user input from the console, we can do the following.
Scanner scn = new Scanner (System.in);
int x;
x = scn.nextInt(); //Receive integer input
In C#, I am assuming we do this:
int x;
x = Console.Read(); //Receive integer input
But when I enter 7 , the output is 55.
The other 2 options for reading inputs are ReadLine() which is probably used for reading strings, and ReadKey() which is proabably for detecting which key you pressed (Please correct me if I am wrong).
Please don't tell me that we have to use ReadLine and parse the entire value to int everytime, that will be awful :-(
EDIT: In SO, a similar question was raised (c# Console.Read() and Console.ReadLine() problems), but all the solutions given was to use int.TryParse and series of codes just to receive a int or double input, which I find it too inconvenient just to do a simple task.
I found out that we could actually do this:
int a = int.Parse(Console.ReadLine());
So instead of asking a duplicated question,
my new question is: Is it equivalent to Java's scn.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?
Is it equivalent to Java's scanner.nextInt() when I use int a = int.Parse(Console.ReadLine()); to receive int inputs?
Yes. Java's Scanner.nextInt() throws an exception when no integer input has been received, as does .NET's int.Parse(Console.ReadLine()).
This may be a year late, but...
static int GetInt() {
int integer = 0;
int n = Console.Read();
while (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
n = Console.Read();
while (n >= '0' && n <= '9') {
integer = integer * 10 + n - '0';
n = Console.Read();
}
return integer;
}
This is more or less the same as Java's nextInt() method. It doesn't support negative values as it currently is, but it can be easily implemented by checking if the first read value is '-' and if it is, multiply the final value by -1.
Yes, you need to use ReadLine, parsing the input is not so hard.Just use TryParse method:
int input;
bool isValid = int.TryParse(Console.ReadLine(),out input);
if(isValid)
{
...
}
Console.Read reads the next character from console, and it returns the ASCII code of the char, that's why you are getting 55 instead of 7.
You can use this library from NuGet which provides Java Scanner/C++ cin style input in C#: https://www.nuget.org/packages/Nakov.IO.Cin/
Sample:
using System;
using Nakov.IO;
public class EnterNumbers
{
static void Main()
{
int n = Cin.NextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
numbers[i] = Cin.NextInt();
for (int i = 0; i < n; i++)
Console.Write(numbers[i] + " ");
}
}

C# How to Remove leading 0's from 32bit int

I ran into this question when watching the twit.tv show coding 101 (episode 2). The code was pre written, but we were asked to change it in order to print out all the values of the while loop that converted an integer to a binary number.
I was able to print out everything with a simple "Console.WriteLine(number);" line. When doing so, it returns all the values for the 32-bit int 0's included.
My question, is there a way to trim or remove all the extra 0's in the division of the loop (not in the final binary number) so they are not printed? Here is the code of the program:
public static string ConvertIntToBinary(int number)
{
int bits = (sizeof(int) * 16); //32bits
char[] result = new char[bits]; //Array to hold the binary numbers http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
while (bits > 0)
{
bits = bits - 1;
int remainder = number % 2; //% called mod or modulo which computes the remainder after dividing http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
if (remainder == 1) //If remainder is 1, store it as 1
result[bits] = '1';
else
result[bits] = '0'; //Otherwise store it as 0
number = number / 2; //Take the original number, divide it by 2
Console.WriteLine(number);
}
return new string(result).TrimStart('0'); //return the result as a string ,removing extra 0's
}
Terminate the loop when number reaches 0. At that point there are no more non-zero bits to pull off:
public static string ConvertIntToBinary(uint value)
{
int totalbits = sizeof(int) * 8;
char[] result = new char[totalbits];
int bits = totalbits;
uint number = value;
while (bits > 0)
{
bits--;
uint remainder = number % 2;
result[bits] = remainder == 0 ? '0' : '1';
number /= 2;
if (number == 0)
break;
}
return new string(result, bits, totalbits - bits);
}
I fixed an error in the code: there are 8 bits in a byte, and not 16 as per your code. I also simplified a few parts of the code. I used a conditional expression which is more concise than the if. And I introduced another local variable to hold the working value to avoid modifying the actual parameter. This is generally good practise that makes debugging easier. I also used uint for the input parameter since the entire approach depends on the value being positive.
Note that the termination is inside the loop rather than in the while test. If you test for number equal to 0 in the while condition then you will end up returning the empty string for an input of 0.
Just ignore all the Zero bits as you loop until you hit a '1' bit.
This works with negative numbers as well.
public static string ConvertIntToBinary(int number)
{
if (number == 0) return "0";
var bits = (sizeof(int) * 8); // 8bits per byte
var sb = new StringBuilder();
var print = false;
var mask = (uint)(1 << bits - 1);
while (bits-->0)
{
var bit = (number & mask) == mask;
if (bit) print = true;
if (print) sb.Append(bit ? '1' : '0');
mask = mask >> 1;
}
return sb.ToString();
}

Programmatically check if a number is a palindrome

This sounds like homework, yes it is (of someone else), I asked a friend of mine who is learning C# to lend me some of his class exercises to get the hang of it.
So as the title says: How can I check if a number is a Palindrome?
I'm not asking for source code (although its very useful), but rather that someone explained how should the code should work, so that it can be applied to many different languages.
The Solution:
#statikfx searched SO for this and found the solution.
n = num;
while (num > 0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
// If (n == rev) then num is a palindrome
I check for palindromes by converting the integer to a string, then reversing the string, then comparing equality. This will be the best approach for you since you're just starting out.
Since you're working in C# and this is homework, I'll use very obscure-looking Python that won't help you:
def is_palindrome(i):
s = str(i)
return s[::-1] == s
Convert that to C# and you'll have your answer.
Main idea:
Input number: 12321
Splitting the digits of the number, put them into an array
=> array [1, 2, 3, 2, 1]
Check if array[x] = array[arr_length - x] for all x = 0..arr_length / 2
If check passed => palindrome
There are many ways. Probably the simplest is to have 2 indexes, i at beginning and j at end of number. You check to see if a[i] == a[j]. If so, increment i and decrement j. You stop when i > j. When looping if you ever reach a point where a[i] != a[j], then it's not a palindrome.
Here's some working code. The first function tests if a number is palidromic by converting it to a string then an IEnumerable and testing if it is equal to its reverse. This is enough to answer your question. The main function simply iterates over the integers testing them one by one.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static bool IsPalindromic(long l)
{
IEnumerable<char> forwards = l.ToString().ToCharArray();
return forwards.SequenceEqual(forwards.Reverse());
}
public static void Main()
{
long n = 0;
while (true)
{
if (IsPalindromic(n))
Console.WriteLine("" + n);
n++;
}
}
}
Update: Here is a more direct method of generating palindromes. It doesn't test numbers individually, it just generates palindromes directly. It's not really useful for answering your homework, but perhaps you will find this interesting anyway:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main()
{
bool oddLength = true;
ulong start = 1;
while (true)
{
for (ulong i = start; i < start * 10; ++i)
{
string forwards = i.ToString();
string reverse = new string(forwards.ToCharArray()
.Reverse()
.Skip(oddLength ? 1 : 0)
.ToArray());
Console.WriteLine(forwards + reverse);
}
oddLength = !oddLength;
if (oddLength)
start *= 10;
}
}
}
My solution:
bool IsPalindrome(string str)
{
if(str.Length == 1 || str.Length == 0) return true;
return str[0] == str[str.Length-1] && IsPalindrome(str.Substring(1,str.Length-2));
}
Here's some pseudocode:
function isPalindrome(number) returns boolean
index = 0
while number != 0
array[index] = number mod 10
number = number div 10
index = index + 1
startIndex = 0;
endIndex = index - 1
while startIndex > endIndex
if array[endIndex] != array[startIndex]
return false
endIndex = endIndex - 1
startIndex = startIndex + 1
return true
Note that that's for base 10. Change the two 10s in the first while loop for other bases.
The following function will work for both numbers as well as for strings.
public bool IsPalindrome(string stringToCheck)
{
char[] rev = stringToCheck.Reverse().ToArray();
return (stringToCheck.Equals(new string(rev), StringComparison.OrdinalIgnoreCase));
}
zamirsblog.blogspot.com
in theory you want to convert the number to a string. then convet the string to an array of characters and loop the array comparing character (i) with character (array length - i) if the two characters are not equal exit the loop and return false. if it makes it all the way through the loop it is a Palindrome.
Interesting. I'd probably convert the number to a string, and then write a recursive function to decide whether any given string is a palendrome.
int n = check_textbox.Text.Length;
int check = Convert.ToInt32(check_textbox.Text);
int m = 0;
double latest=0;
for (int i = n - 1; i>-1; i--)
{
double exp = Math.Pow(10, i);
double rem = check / exp;
string rem_s = rem.ToString().Substring(0, 1);
int ret_rem = Convert.ToInt32(rem_s);
double exp2 = Math.Pow(10, m);
double new_num = ret_rem * exp2;
m=m+1;
latest = latest + new_num;
double my_value = ret_rem * exp;
int myvalue_int = Convert.ToInt32(my_value);
check = check - myvalue_int;
}
int latest_int=Convert.ToInt32(latest);
if (latest_int == Convert.ToInt32(check_textbox.Text))
{
MessageBox.Show("The number is a Palindrome number","SUCCESS",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
MessageBox.Show("The number is not a Palindrome number","FAILED",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
public class Main {
public static boolean Ispalindromic(String word) {
if (word.length() < 2) {
return true;
}
else if (word.charAt(0) != word.charAt(word.length() - 1)) {
return false;
} else {
Ispalindromic(word.substring(1, word.length() - 1));
}
return true;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String word = sc.nextLine();
System.out.println(Ispalindromic(word) ? "it is palidromic" : "it is not palidromic");
}
}
This is my solution coming from a beginner:
Console.Write("Enter a number to check if palindrome: ");
bool palindrome = true;
int x = int.Parse(Console.ReadLine());
/* c is x length minus 1 because when counting the strings
length it starts from 1 when it should start from 0*/
int c = x.ToString().Length - 1;
string b = x.ToString();
for (int i = 0; i < c; i++)
if (b[i] != b[c - i])
palindrome = false;
if (palindrome == true)
Console.Write("Yes");
else Console.Write("No");
Console.ReadKey();
You need to reverse the number then compare the result to the original number.
If it matches, you have a palindrome. It should work irrespective of the number being even, odd or symmetric.
public static bool IsNumberAPalindrome(long num)
{
return long.Parse(string.Join("", num.ToString().ToCharArray().Reverse().ToArray())) == num ? true : false;
}
The implementation is bellow:
public bool IsPalindrome(int x) {
string test = string.Empty;
string res = string.Empty;
test = x.ToString();
var reverse = test.Reverse();
foreach (var c in reverse)
{
res += c.ToString();
}
return test == res;
}
You have a string, it can have integers, it can have characters, does not matter.
You convert this string to an array, depending on what types of characters the strings consist of, this may use to toCharArray method or any other related method.
You then use the reverse method that .NET provides to reverse your array, now you have two arrays, the original one and the one you reversed.
You then use the comparison operator (NOT THE ASSIGNMENT OPERATOR!) to check if the reversed one is the same as the original.
something like this
bool IsPalindrome(int num)
{
var str = num.ToString();
var length = str.Length;
for (int i = 0, j = length - 1; length/2 > i; i++, j-- ){
if (str[i] != str[j])
return false;
}
return true;
}
you could even optimise it

Categories