public static bool IsPalindrome(long number) { bool isPalin = true; // inefficient solution - convert number to string string numAsStr = number.ToString(); // more inefficiency - looping through the entire string // could have achieved the same by traversing just half the string for (int i = 0, j = numAsStr.Length - 1; i < numAsStr.Length - 1; i++, j--) { if (numAsStr[i] != numAsStr[j]) { // the corresponding locations do not match isPalin = false; // some people forget to break out of the loop // extremely bad - no need to do any further comparisons break; } } return isPalin; }
The above solution was an in-efficient solution. It works, but does not get you any points. So, now let's see what improvements can be made to the above program.
public static bool IsPalindrome2(long number) { bool isPalin = true; // inefficient solution - convert number to string string numAsStr = number.ToString(); // we can find if a string is palindrome or not by just traversing half the string for (int i = 0, j = numAsStr.Length - 1; i < (numAsStr.Length) / 2; i++, j--) { if (numAsStr[i] != numAsStr[j]) { // the corresponding locations do not match isPalin = false; // some people forget to break out of the loop // extremely bad - no need to do any further comparisons break; } } return isPalin; }
In the above solution, we cut our execution time by almost half. Better, but not good enough. At this point, the interviewer should have a pretty good idea of your skills on reviewing code and making changes to improve it. Let's assume that he still wants you to keep digging.
public static bool IsPalindrome3(long number) { // since the input is a number, one very fast way way would be // to reverse the number and compare to original long revNum = ReverseNumber(number); return (number == revNum); } private static long ReverseNumber(long number) { long retVal = 0; do { // get the last digit by using the modulo (remainder) operator retVal = (retVal * 10) + (number % 10); // drop the last digit from the number number = number / 10; } while (number != 0); return retVal; }
If you run some performance tests with larges number sets on the above solutions, you will find that the 3rd solution is the most performant. I hope this example has shown you one way to attempt to solve a coding question. Remember, it is not just about the answer. The interviewer is trying to find your ability to think, debug and troubleshoot a problem.
Great example!
ReplyDeleteMore examples of programming elegance please :)
class Palindrome
ReplyDelete{
static void Main()
{
string checkStr, sampleStr;
char[] temp;
System.Console.Write("Enter your String: ");
sampleStr = System.Console.ReadLine();
checkStr = sampleStr.Replace(" ", "");
checkStr = checkStr.ToLower();
temp = checkStr.ToCharArray();
System.Array.Reverse(temp);
if(checkStr== new string(temp))
{
System.Console.WriteLine(""{0}" is a palindrome.",sampleStr);
}
else
{
System.Console.WriteLine(""{0}" is NOT a palindrome.",sampleStr);
}
}
}
gayathri,
DeleteThe goal of this exercise is to not use built-in functions. You need to show that you understand how the system works underneath and that you can get the best performance possible.
if(sampleStr==new String(temp)),correct it ;-)
Deletetry this for numbers very simple logic..
Deleteclass palindrom
{
static void main()
{
int num,rem,temp,rev=0;
Console.WriteLine("eneter no");
num=int.parse(Console.ReadLine());
num=temp;
while(num>0)
{
rem=num%10;
rev=rev*10+rem;
num/=10;
}
if(temp==rev)
WriteLine("no is palindrome");
else
(not palindrome");
}
}
Great collection of questions in one plate!
ReplyDeleteThe last solution is so smart :)
ReplyDeleteclass Program
ReplyDelete{
static void Main(string[] args)
{
Console.WriteLine("enter string");
string name = Console.ReadLine();
Boolean palindrome =false;
int len = name.Length;
for (int i = 0; i < (len - 1); i++)
{
if (name[i] == name[len - 1])
{
palindrome = true;
i++;
}
else
{
break;
}
}
if (palindrome == true)
{
Console.WriteLine(" ur name is palindrome");
Console.ReadKey();
}
else
{
Console.WriteLine(" ur name is not a palindrome");
Console.ReadKey();
}
}
}
Vivek,
DeleteTake a look at the third solution in my post. Why would you want to traverse the entire length of the string when in fact you can get the answer in half?
Vivek,
Deletejust change insted of i++; write len--; and else past write palindrome=false;
then u r code is working fine
Let me try this one in ruby:
ReplyDeletedef palindrome?(n)
digits = Math.log10(n).to_i + 1
(digits/2).times do |right|
left = digits-1-right
if n/(10*left)%10 != n/(10*right)%10
return false
end
end
return true
end
Btw, I can't seem to post in safari, but works in chrome....
@Nikhil Singhal :
ReplyDeleteI tried the second example you gave in your post above which traverse only half the string. But i think its wrong. because when the user enters a number such as "4254", the variable "isPalin" is considered true, and the for loop breaks out after the firs iteration as numtoStr[0] = 4 and numtoStr[3]=4
Imad,
DeleteThe loop will execute 2 times as length/2 is 4/2 = 2 and the counter starts at 0. So, in two iterations, the string will be reversed. I would strongly recommend that you type this code in a program and execute it step by step.
ReverseNumber function doesn't work for numbers that end in zero. For example try 120 and it returns 21
ReplyDeletehaha. Never mind. Duh, 120 reversed is actually 21!! Sorry. Thanks for this great blog and articles. This is helping me a lot!
ReplyDeleteGood explanation .. Thanks for the post...
ReplyDeleteWhat would your impression be of this approach?
ReplyDeleteprivate static bool isPalidrome(int num)
{
return num.ToString() == new string(num.ToString().Reverse().ToArray());
}
Sure. It would work. But think about the performance implications of your code. What if the string is a million characters long? What complexity and memory pressure are you adding?
DeleteHere is the algo to check number is palindrome or not
ReplyDelete1. Reverse the digits of inputNumber, and store it in another integer variable(Let's call it reverseNumber).
2. Compare inputNumber and reverseNumber.
http://www.techcrashcourse.com/2014/10/c-program-check-palindrome-number.html
Great Article..
ReplyDeleteDot Net Training in Chennai
.Net Online Training
ASP.NET Training
C# Training
C# Online Training
C-Sharp Training
I have an doubt I'm new to c# can I just know to call this method in main method .I don't know how to do that
ReplyDeleteusing System;
ReplyDeletenamespace palindrome
{
class Program
{
static void Main(string[] args)
{
string s,revs="";
Console.WriteLine(" Enter string");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0; i--) //String Reverse
{
revs += s[i].ToString();
}
if (revs == s) // Checking whether string is palindrome or not
{
Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
else
{
Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
Console.ReadKey();
Console.Readline();
}
}
}
I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. I like play game five nights at freddy’s 4, game word cookies game , game hill climb racing 2 , hotmail login, and u? I hope people visit my website.
ReplyDeleteشركة مكافحة النمل الابيض بحائل شركة مكافحة حشرات بحائل
ReplyDelete
ReplyDeleteمن أكثر الأمور التي يجب علينا أن نقوم بالاهتمام بها هي مكافحه الحشرات لان الحشرات المنزلية عندما تتواجد داخل المنزل فأنها تؤدى إلى عواقب وخيمة جدا في هذا المنزل الصفرات لمكافحة الحشرات بالرياض ومن أهم هذه العواقب هي الأمراض الكثيرة التي تأتي إلينا بسبب هذه الحشرات المزعجة لان الحشرات تكون ملوثه وتخرج من البالوعات وتخرج أيضا من المجاري وفي هذه الحالة تكون الحشرات تشكل خطر كبير جدا الصفرات لرش المبيدات بالرياض على جميع أفراد الأسرة وعلى جميع الأفراد المتواجدين داخل المنزل وخاصة للأطفال الصغار ولذلك يجب علينا أن نقوم بالاهتمام بهذا الأمر وان نقوم برش المبيدات الحشرية داخل المنزل بطريقه سليمة وأمنه الصفرات لرش المبيدات وان نقوم بعلاج هذه المشكلة طوال الوقت حتى نقوم بالقضاء على أي حشرات تتواجد داخل منزلنا و حتى نجعل البيت نظيف تماما من أي حشرات .
تعتبر شركتنا افضل كشف تسربات المياه بجده داخل المملكه حيث ان شركتنا لديها قدره كبيره جدا علي معرفه اماكن التسربات وتضع لكم الحل الامثل للقضاء الصفرات للعزل علي هذه المشكله فنحن نقدم لكم خدمه فريده من نوعها والقضاء علي مشاكل التسربات تماما فنحن نعمل وفق منظومه عمل متكامله الصفرات لكشف لتسربات المياه وراقيه جدا ونقدم لكم افضل اسليب الكشف وارقاها علي الاطلاق ونوفر اسلوب فني عالي جدا ونجتهد لنخرج لكم عمل يليق بكم ويليق باسم شركتنا الكبير جدا لان شركتنا هي اكبر.
العميل نبداء مباشرة وانة يتم هذا عقب تحديد المشكلة الأساسية ويكون من خلال اجهزة تسليك البالوعات المتطورة هو الحل حيث ان إستعمال الاسيد لفتح المجارى ليس يُعد الحل الامثل و الاسرع فى وسيلة تسليك البلاعة و فتح المجاري المقفلة الصفرات لتسليك المجاري ويكون بلا تكسير وإذ لم يكن لك التمكن في تسليك المجارى واذا كنت لا تعرف العلة فى انسداد المرحاض.
هي إزالة الأوساخ والقاذورات والنفايات من أي مكان والنظافة عبارة عن ممارسات يومية أو أسبوعية أو شهرية ويجب التنظيف بشكل دوري لأن نظافة المكان تؤدي خدمة المنزل بالرس إلى أفض صحة بالنسبة للأفراد ويؤدي إلى منع انتشار الأمراض والأوبئة بالمكان، وأن نظافة تؤدي إلى راحة نفسية شركة تنظيف بالرس والشعور بالسعادة
أن النظافة أساس كل تقدم ورقي، عنوان الحضارة شركة تنظيف خزانات بالمدينة المنورة ، ومظهر من مظاهر الإيمان .
ReplyDeleteشركه عزل فوم بالدمام
ReplyDeleteشركة تنظيف بالباحة التنظيف من الأشياء المهمة التي يجب الاهتمام بها فهناك العديد من الشركات التي تقوم بعمل التنظيف بشكل ممتاز كما تعمل بدقة كبيرة وكفاءة عالية.
فيتم التنظيف بعدة طرق مختلفة ولكن تحتاج الى ايدي عاملة مثل شركة تنظيف بالباحة
حتى يتم العمل على أفضل وجه فيجب القيام بالتنظيف باستخدام مواد التنظيف التي تتناسب مع كل ما تقوم بتنظيفه سواء كان سجاد او أثاث أو ستائر أو أرضيات أو غيرها من الاشياء الاخرى والاماكن الاخرى.
فتحتاج عند القيام بالتنظيف إلى أدوات تعمل على التنظيف بشكل جيد وبطريقة جيدة تنظف بعمق ولكنها لاتتلف الاشياء الخاصة بالمنزل.
كما يجب أيضا الاهتمام بالتعقيم للحمامات والمطابخ والتنظيف بدقة لأن تلك الاماكن أكثر تعرضا في بيتك او منزلك للاتساخات بشكل كبير شركة تنظيف بالباحة
وتحتاج إلي التنظيف بشكل مستمر .
كما أن هناك أيضا العديد من الاشخاص الذين يعانون من الاتساخات الموجودة بالاثاث والكنب بمختلف أنواعه فلكل نوع من أنواع الكنب طريقة مختلفة عن الاخري في التنظيف سواء كان من الجلد أو قماش أو مغطى بالخشب فيجب تحديد نوع المنظف الذي تقوم باستخدامه في التنظيف قبل الاستخدام حتى لا يتسبب في أي ضرر للكنب أو للاثاث.
لا تقتصر عمليات التنظيف علي مكان محدد دون الآخر بل إنها من الأمور الهامه لجميع الأماكن سواء كانت منازل أو فلل أو شقق وايضا جميع أنواع الاثاث وخاصه السجاد والانتريهات الذي تتراكم فيه الاوساخ والأتربة والروائح الكريهه.
كما يجب أن تتم عملية التنظيف للخزان أيضا والذي يعتبر من أهم الأغراض في كل منزل، ومن أهم أساليب النظافة أن يتم مراعاه التنظيف الجيد لمواسير الصرف والمجاري التي تعتبر من أكثر الأماكن التي تتعرض للانسداد وتراكم الحشرات بها وتتسبب في الأمراض.
كما يجب أن تتضمن عملية التنظيف أيضا التخلص من القاذورات بشكل مستمر وعدم تراكمها في المنزل فهي من أهم أسباب انتشار الحشرات والروائح الكريهه والتي هي مصدر للأمراض المختلفه.
النظافة من الأمور الضرورية والتي يحثنا عليها الدين الإسلامي وتتطلب تنفيذ دقيق واتباع الخطوات التي توفر اعلي نسب حمايه ممكنه والتخلص من مشاكل المنازل التي تنتج عن انتشار هذه الاوساخ المزعجه.
شركة عزل أسطح
من المعروف ان عزل الأسطح من المهام التي من الممكن ان تقوم بيه شركة عزل أسطح فهي من المهام التي من الممكن ان تساهم بشكل كبير في حماية الأسطح شركة عزل اسطح بالباحة
وهذا من الكثير من العوامل الضارة والتي من الممكن ان تؤثر على الأسطح
Thanks for sharing information to our knowledge, it helps me plenty keep sharing…
ReplyDeleteApache Spark Training in Pune
Spark Training Institute in Pune
Đại lý vé máy bay Aivivu
ReplyDeletevé máy bay đi Mỹ
vé máy bay từ mỹ về việt nam
lịch bay từ canada về việt nam
gia ve may bay tu han quoc ve viet nam
khi nào có chuyến bay từ anh về việt nam
lịch bay từ pháp về việt nam
bao giờ có chuyến bay từ đức về việt nam
giá vé máy bay từ nga về việt nam
thời gian bay từ Việt nam sang Los Angeles
chi phí cách ly khách sạn