Palindrome is not working [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I check if a number is a palindrome?
Hello All i want to make program to check whether palindrome number or not when user input the number. But my work does not work at all... Can you guys help me...
class Program
{
static void Main(string[] args)
{
int i = 0, j = 0 ;
int numbers =Convert.ToInt32( Console.ReadLine());
i = numbers % 10;
do
{
j = numbers / 10;
}
while (j < 10);
if (i == j)
{
Console.WriteLine(" this is palindrome number");
}
else
{
Console.WriteLine("not a palindrome");
}

The quickest way is to reverse the string and compare it to the original. You don't really need the integer conversion.
You may want to filter or correct the user's input by stripping leading zeroes (i.e. in 010). For example : string number = Convert.ToInt32(Console.ReadLine()).ToString();

You don't have to convert it to integer.
You can check it from the string.
Take the first character and the last character compare those .
Iterate the first pointer +1 and the last pointer -1 then compare.
Continue this process upto you are in middle of the string.

First of all by converting the digits to an Int32, the number of digits a user can enter are limited.
By using the modulo operation, the i variable will contain the last digit of the entered number.
By dividing the number by 10, j should eventually contain the first digit entered. However you aren't dividing it "until j is smaller than 10", but you're dividing it "while j is smaller than 10", effectively making the contents of j depend on the number of digits entered.
Even if you would fix the while condition, this code will only check the first and last digit, making it function only for 1, 2 and 3 digit numbers.

You'll need something like this:
bool isPalindrome = true;
string s = "300212003";
for (int i = 0; i < (s.Length / 2); i++)
{
if (s[i] != s[s.Length - i - 1])
{
isPalindrome = false;
break;
}
}
Console.WriteLine(isPalindrome);
It's faster than reverting a string and comparing it, only need O(n/2) operations.

a disscussion
palindrome check
C# code to check palindrome
You can follow these links .
#include<stdio.h>
#include<math.h>
void main()
{
long int n, num, rev = 0, dig;
clrscr();
printf("\n\n\t ENTER A NUMBER...: ");
scanf("%ld", &num);
n = num;
while(num>0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
if (n == rev)
printf("\n\t GIVEN NUMBER IS A PALINDROME");
else
printf("\n\t GIVEN NUMBER NOT A PALINDROME");
getch();
}

Something is palindrome when you can read it either way, so when the reverse is the same as the original.
So just reverse your input string and compare it to the original.

Related

How do I take multiple input in the same line in C#? [duplicate]

This question already has answers here:
Read numbers from the console given in a single line, separated by a space
(7 answers)
Closed 2 years ago.
I'm new to C# programming. I was wondering how do you take multiple inputs in one line. My code:
using System;
namespace ArrayExercise01
{
class Program
{
static void Main(string[] args)
{
int arraySize = int.Parse(Console.ReadLine());
int[] ar = new int[arraySize];
int i;
for(i=0; i<arraySize; i++)
{
Console.Write("");
ar[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int arrayElement in ar)
{
sum += arrayElement;
}
Console.WriteLine(sum);
}
}
}
I get this output after running this:
3
2
3
4
9
But I wanted to do something like this (Multiple Input in single line):
3
2 3 4
9
Instead of:
ar[i] = int.Parse(Console.ReadLine());
You could:
foreach(string s in Console.ReadLine().Split()){
ar[i] = int.Parse(s);
i++;
}
Split without any arguments splits on whitespace, of which is one.. So the user is prompted for a string , and they could enter 1 or 1 2 3 4 5 or any combination (though there will be a problem if they enter more numbers than the remaining array can hold). The code splits them on the space, to become five strings of "1" "2" "3" "4" "5", and then the loop runs 5 times, and each one is parsed in turn and stored in an array index. The index i is incremented each time
As well as checking that i is still within the length of the array, it would be advisable to skip bad input too; take a look at int.TryParse, which returns a boolean false if the parsing did not succeed; if it returns false, don't add to the array/don't increment i
As per your requirement of "take multiple input on same line" you could do this as follow
List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
but there is a problem while we take multiple input on same line as "we can't restrict user to enter only given size of numbers". To avoid this we can give informative message(or we can say validation message) to user as follows
while (numbers.Any() && ((numbers.Count() < arraySize) || (numbers.Count() > arraySize)))
{
Console.WriteLine("You have enter the numbers might be less than or greater than given size");
Console.WriteLine("Please the numbers of given size");
numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
}
Finally, you can do sum as follows
int sum = 0;
foreach (var num in numbers)
{
sum += num;
}
//or you can use directly sum method as follows
//Console.WriteLine(numbers.Sum());
Program as follows
static void Main(string[] args)
{
int arraySize = int.Parse(Console.ReadLine());
List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
while (numbers.Any() && ((numbers.Count() < arraySize) || (numbers.Count() > arraySize)))
{
Console.WriteLine("You have enter the numbers might be less than or greater than given size");
Console.WriteLine("Please the numbers of given size");
numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
}
int sum = 0;
foreach (var num in numbers)
{
sum += num;
}
//or you can use directly sum method as follws
//Console.WriteLine(numbers.Sum());
Console.WriteLine(sum);
Console.Read();
}
Results:
3
1 2
You have enter the numbers might be less than or greater than given size
Please the numbers of given size
1 2 3 4
You have enter the numbers might be less than or greater than given size
Please the numbers of given size
1 2 3
6
Try this, but be careful, inputting too many numbers will cause IndexOutOfRangeException.
for (int i = 0; i < arraySize; )
{
// first catch the input
string input = Console.ReadLine();
// split it by space
string[] everyNumber = input.Split(' ');
for (int j = 0; j < everyNumber.Length; j++)
{
// parse each number in string array
ar[i] = int.Parse(everyNumber[j]);
i++;
}
}

Incorrect values when converting char digits to int

My end goal is to take a number like 29, pull it apart and then add the two integers that result. So, if the number is 29, for example, the answer would be 2 + 9 = 11.
When I'm debugging, I can see that those values are being held, but it appears that other values are also being incorrect in this case 50, 57. So, my answer is 107. I have no idea where these values are coming from and I don't know where to begin to fix it.
My code is:
class Program
{
static void Main(string[] args)
{
int a = 29;
int answer = addTwoDigits(a);
Console.ReadLine();
}
public static int addTwoDigits(int n)
{
string number = n.ToString();
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total = total + a[i];
}
return total;
}
}
As mentioned the issue with your code is that characters have a ASCII code value when you cast to int which doesn't match with the various numerical digits. Instead of messing with strings and characters just use good old math instead.
public static int AddDigits(int n)
{
int total = 0;
while(n>0)
{
total += n % 10;
n /= 10;
}
return total;
}
Modulo by 10 will result in the least significant digit and because integer division truncates n /= 10 will truncate the least significant digit and eventually become 0 when you run out of digits.
Your code is actually additioning the decimal value of the char.
Take a look at https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
Decimal value of 2 and 9 are 50 and 57 respectively. You need to convert the char into a int before doing your addition.
int val = (int)Char.GetNumericValue(a[i]);
Try this:
public static int addTwoDigits(int n)
{
string number = n.ToString();
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total = total + (int)Char.GetNumericValue(a[i]);
}
return total;
}
Converted number to char always returns ASCII code.. So you can use GetNumericValue() method for getting value instead of ASCII code
Just for fun, I thought I'd see if I could do it in one line using LINQ and here it is:
public static int AddWithLinq(int n)
{
return n.ToString().Aggregate(0, (total, c) => total + int.Parse(c.ToString()));
}
I don't think it would be particularly "clean" code, but it may be educational at best!
You should you int.TryParse
int num;
if (int.TryParse(a[i].ToString(), out num))
{
total += num;
}
Your problem is that you're adding char values. Remember that the char is an integer value that represents a character in ASCII. When you are adding a[i] to total value, you're adding the int value that represents that char, the compiler automatic cast it.
The problem is in this code line:
total = total + a[i];
The code above is equal to this code line:
total += (int)a[i];
// If a[i] = '2', the character value of the ASCII table is 50.
// Then, (int)a[i] = 50.
To solve your problem, you must change that line by this:
total = (int)Char.GetNumericValue(a[i]);
// If a[i] = '2'.
// Then, (int)Char.GetNumericValue(int)a[i] = 2.
You can see this answer to see how to convert a numeric value
from char to int.
At this page you can see the ASCII table of values.
public static int addTwoDigits(int n)
{
string number = n.ToString()
char[] a = number.ToCharArray();
int total = 0;
for (int i = 0; i < a.Length; i++)
{
total += Convert.ToInt32(number[i].ToString());
}
return total;
}
You don't need to convert the number to a string to find the digits. #juharr already explained how you can calculate the digits and the total in a loop. The following is a recursive version :
int addDigit(int total,int n)
{
return (n<10) ? total + n
: addDigit(total += n % 10,n /= 10);
}
Which can be called with addDigit(0,234233433)and returns 27. If n is less than 10, we are counting the last digit. Otherwise extract the digit and add it to the total then divide by 10 and repeat.
One could get clever and use currying to get rid of the initial total :
int addDigits(int i)=>addDigit(0,i);
addDigits(234233433) also returns 27;
If the number is already a string, one could take advantage of the fact that a string can be treated as a Char array, and chars can be converted to ints implicitly :
var total = "234233433".Sum(c=>c-'0');
This can handle arbitrarily large strings, as long as the total doesn't exceed int.MaxValue, eg:
"99999999999999999999".Sum(x=>x-'0'); // 20 9s returns 180
Unless the number is already in string form though, this isn't efficient nor does it verify that the contents are an actual number.

Print all unique digit numbers

Question: Print all the number who has unique digits only.
Input : n =15
output: 1 2 3 4 5 6 7 8 9 10 12 13 14 15
Here 11 is not included because it has 1 two times, same way 123, 456 .. are also valid but 121 1344 are not valid because there is same digit more than once.
I am running loop from 1- n and checking each number.
I am using Hash-map to determine the uniqueness of number.
Is there any better solution of above problem.
i'm not sure , but something like that..
List<int> numbers = new List<int>(){};
numbers =numbers.Where(p=>validCheck(p)==true).ToList();
static bool validCheck(int n)
{
return (n.ToString().Length==n.ToString().Disctinct().Count());
}
You could use LINQ, convert the number into a string and check if the length of the string is equal to the number of distinct charchters.
for (int i = 1; i < n; i++){
if (i.ToString().Length == i.ToString().Distinct().Count())
Console.Out.Write(i + " ");
}
as a semi useful library function where you seed it with a start and how many you want.
public static IEnumerable<int> UniqueDigits(int start, int count)
{
for (var i = start; i < (start + count); i++)
{
var s = i.ToString();
if (s.Distinct().Count() == s.Length)
{
yield return i;
}
}
}
then
UniqueDigits(0,15).ToList().ForEach(Console.WriteLine);
or
foreach (var digit in UniqueDigits(100,50))
{
Console.WriteLine(digit);
}
This is how I eliminate the numbers that have a duplicate characters.
Console.Write("Input:");
int number = int.Parse(Console.ReadLine());
List<int> numbers = new List<int>();
List<int> acceptedNumbers = new List<int>();
for (int i = 1; i <= number; i++)
{
numbers.Add(i);
}
foreach (var num in numbers)
{
bool rejected = false;
char[] numChars = num.ToString().ToCharArray();
foreach (var numChar in numChars)
{
if (numChars.Where(n => n == numChar).Count() > 1)
{
rejected = true;
}
}
if (!rejected)
{
acceptedNumbers.Add(num);
}
}
acceptedNumbers.ForEach(n => Console.Write($"{n} "));
Console.Read();
A string is an IEnumerable - so you can use a LINQ statement to solve your problem:
Numbers.Where(N => N.ToString().Distinct().Count() == N.ToString().Length);
The query is checking how many characters of the string of your number distinct and comares this number with the number of total characters.
Here is the whole code printing out all distinct numbers until 20:
List<int> Numbers = new List<int>();
for (int i = 1; i <= 20; i++)
{
Numbers.Add(i);
}
IEnumerable<int> AcceptedNumbers = Numbers.Where(N => N.ToString().Distinct().Count() == N.ToString().Length);
foreach (int AcceptedNumber in AcceptedNumbers)
{
Console.WriteLine(AcceptedNumber);
}
My thoughts:
Run the Loop from 0 to n
For each batch of 10 ( like from 0 to 9 , 10 to 19, 230 to 239..), pick the digits apart from the last one. These digits map to the counter which tends to be skipped. Rest all are to be emitted. For eg : for batch 12x , pick 1 & 2 , now we know that we have to skip numbers at position 1 and 2 , and rest all are acceptable so no need to do any processing for them.
Keep the above digits in sorted manner in an arrayList and keep a pointer at index 0. Lets call it 'ptr'. While running through that batch, check if count ( which moves from 0 to 9 ) for each batch is equal to the array[ptr]. If no, emit the number out. Else, skip it and do ptr++.
When you are doing step 2, check if any digits are duplicate. If yes, skip the entire batch of 10.
There are no string operations happening, so it should bring in the efficiency
Another solution is using integer division and modulo (no number to string conversion). You can verify the uniqueness of a number with the following method (assume digits is int array having 10 elements).
public static bool IsUnique(int num) {
int[] digits = new int[10];
num = Math.Abs(num);
while (num > 0) {
int r = num % 10;
num /= 10;
digits[r] ++;
if (digits[r] > 1) {
return false;
}
}
return true;
}
Working example http://ideone.com/9emEoz
There are only 9 * 9! / (10 - n)! unique-digit numbers with n digits. For larger n, you might want a next lexicographic algorithm to avoid unnecessary iterations. (For example, there are only 544,320 7-unique-digit numbers, yet your program would need to iterate through almost 10 million numbers to produce them!)
Here's my attempt at a next lexicographic procedure for a set of n-unique-digit numbers (where n > 1):
(1) From left to right, start with the digits 10, then ascend from 2.
For example, the first 4-digit number would be 1023.
(2) Increment the right-most digit that can be incremented to the next available
higher digit unused by digits to its left. Ascend to the right of the
incremented digit with the rest of the available digits, starting with lowest.
Examples: 1023 -> 1024 (4 is unused by the digits left of 3)
^
9786 -> 9801 (8 is unused be the digits left of 7)
^
9658 -> 9670 (7 is unused by the digits left of 5)
^

C# number format: display n significant number of digits?

is there a way to format a double value such that it shows the n siginifacant digits only?
for example I have a double with value 123456, can we have a format string such that it displays the first 3 digits only.
double x=12346;
string s=x.ToString("Some format"); //display 123 only
is that possible?
Although there are formats that would let you drop some or all of the fraction, no format would let you drop some of the significant digits of the whole part of the number.
If you would like to keep the first three digits of the whole number, you need to divide the value so that its whole part has only three digits.
One approach to computing the divisor is taking log10N, checking if it is above 2, and dividing by 10 to the corresponding power:
private static void Print(double x) {
int n = (int)Math.Log10(x);
if (n > 2) {
x /= Math.Pow(10, n-2);
}
Console.WriteLine((int)x);
}
Demo.
You can't format the largest part of the double to only be to 3 sig. fig. but you can split the string. Try:
String s = x.ToString().Substring(0, n);
Where n is the number of significant figures you wish to keep.
I made a console application for this example. I know you need a double or int data type for the number, but I didn't know how manipulate the decimal numbers after the point, so I used a string (if you don't mind, store the number value inside string data type):
string number = "";
string digits = "";
int n = 0;
int count = 0;
number = "45.6";
//number = "456";
n = 3;
if (number.Contains('.')) //If the number has decimals...
{
if (n < number.Length)
{
if (number.IndexOf('.') < n)
{
while (count <= n) //... we will count the number in a different way.
{
if (number[count] != '.')
{
digits = digits + number[count];
}
count++;
}
}
else
{
while (count < n)
{
if (number[count] != '.')
{
digits = digits + number[count];
}
count++;
}
}
}
}
else
{
if (n <= number.Length)
{
while (count < n) //If not, we count without the decimal point.
{
digits = digits + number[count];
count++;
}
}
}
Console.WriteLine("N significant digits: " + digits);
You can try with decimal and integer numbers, but in the code, they both are strings. As I said before, if you don't mind using this data type, this example will help you, if not, you can try with "Substring" function from the String class.

Double the alternative digits in a number and add each digit

I am using the following code to double alternative digits from a number and add every digit but its not working in c#
int sum=0,r,number;
Console.WriteLine("Enter the number");
number = int.Parse(Console.ReadLine());
if (number % 2!= 0)
{
number = number * 2;
number++;
}
Console.WriteLine("numbers:" + number);
Console.ReadLine();
while (number!= 0)
{
r = number % 10;
number= number/ 10;
sum = sum + r;
}
Console.WriteLine("sum of digits of the number:" + sum);
Console.ReadLine();
Kindly help me. Thank you in advance.
As StevieB said "You're not doubling alternative digits. You're doubling the number and adding 1 if the original number is odd. Then you're summing the digits of the number."
The following code should work for you. I have not tested it for all possible scenarios so please do so.
Also tweek it a little as per your requirements.
Console.WriteLine("Enter a number:");
char[] enteredNumber = Console.ReadLine().ToArray();
int finalNumber = 0;
for (int i = 0; i < enteredNumber.Count(); i++)
{
if (i % 2 != 0)//This condition might need tweeking
{
finalNumber = finalNumber + (Convert.ToInt32(enteredNumber[i].ToString()) * 2);
}
else
{
finalNumber = finalNumber + Convert.ToInt32(enteredNumber[i].ToString());
}
}
Console.WriteLine(finalNumber);
What you are looking for is Luhn Algorithm which I have reproduced here for you.
Luhn Algorithm - C#
Luhn Algorithm uses the last digit (rightmost digit) as a checksum digit. Hence in my first iteration I skip it since it's not required in the first parts of the function.
Since the length of a given number can vary, I have used int a to check my position and know which number I should double and which I should skip.
Read more about the Luhn Algorithm here.
using System;
public class Program {
public void Main()
{
int sum=0,d;
string oNum = "79927398713";
int a = 0;
for(int i = oNum.Length-2; i>=0;i--)
{
d = Convert.ToInt32(oNum.Substring(i,1));
if (a % 2 == 0) d = d*2;
if (d > 9) d -= 9;
sum += d;
a++;
}
if ((10 - (sum%10)) == Convert.ToInt32(oNum.Substring(oNum.Length-1)))
{
Console.WriteLine("Valid");
}
else
{
Console.WriteLine("Invalid");
}
Console.WriteLine("sum of digits of the number:" + sum);
}
}
There are three places where the Console writes a line. And at least two of those are visible for any given number. The line that you wanted, "sum of digits of the number:" will always show.

Categories

Resources