Imagination about A. NET programmer interview question

Source: Internet
Author: User

A few days ago, I was asked by a programmer, entitled "count the number of times each number appears in a string of numbers entered by the user ".

When I saw this question, my first thought was:

1. First, determine whether the user inputs a number and use the if-else statement to determine;

2. Convert the numeric string you entered into a char array;

3. Use the for loop to traverse each character and judge one by one based on the switch-case statement.

4. Create an int array to receive the result after judgment, and finally output the for loop.

 

The code for solving this problem is as follows:

View Code

Class Program
{
Static void Main (string [] args)
{
// Calculate the number of occurrences of each number in a string entered by the user

Console. WriteLine ("enter a number ");
String str = Console. ReadLine (); // converts a string to a character array.
Char [] chnum = str. ToCharArray ();

# Region determine whether the user input is a number
For (int I = 0; I <chnum. Length; I ++)
{// Identify whether each character is a number using the char Method
If (! Char. IsNumber (chnum [I])
{
Console. WriteLine ("your input is incorrect. Please enter a number ");
Console. ReadKey ();
Return;
}
}

# Endregion

// Define a new array to save the count
Int [] count = new int [9];

# Region for loop Traversal
// For Loop Traversal
For (int I = 0; I <chnum. Length; I ++)
{
Switch (chnum [I])
{
Case '1 ':
Count [0] ++;
Break;
Case '2 ':
Count [1] ++;
Break;
Case '3 ':
Count [2] ++;
Break;
Case '4 ':
Count [3] ++;
Break;
Case '5 ':
Count [4] ++;
Break;
Case '6 ':
Count [5] ++;
Break;
Case '7 ':
Count [6] ++;
Break;
Case '8 ':
Count [7] ++;
Break;
Case '9 ':
Count [8] ++;
Break;
}
}
# Endregion

# Region loop output
For (int I = 0; I <count. Length; I ++)
{
Console. WriteLine ("the number of {0} contained is: {1}", I + 1, count [I]);
}
# Endregion
Console. ReadKey ();

}
}

 

The running effect is as follows:

 

However, this method has two disadvantages: if the user does not enter a number (such as letters or symbols), the program will prompt an error and exit, it will also calculate that the number of numbers that the user has not entered is 0. If you do not want to know the number of numbers that have not been entered, this solution is not suitable, the Code is also complex to modify.

 

New Solution: Generic set

It happened that these days I had access to generic collections and did not expect to use Dictionary to solve this problem.

The Code is as follows:

 

View Code

Class Program
{
Static void Main (string [] args)
{
Console. WriteLine ("enter a number ");
String numbers = Console. ReadLine ();
// Create a set key of the numeric char type value of the int type for each number
Dictionary <char, int> dict = new Dictionary <char, int> ();
// Convert a numeric string to a single character array
Char [] chs = numbers. ToCharArray ();
For (int I = 0; I <chs. Length; I ++)
{
// Determine whether it is a number using the isnumber method of char
If (char. IsNumber (chs [I])
{
// If the key already contains this number, add the corresponding value to + 1. Otherwise, the key does not exist and the value is 1.
If (! Dict. ContainsKey (chs [I])
{
// Save each numeric character as a key to a key-value pair. The value is initially 1
Dict. Add (chs [I], 1 );
}
Else
{
// Value + 1
Dict [chs [I] ++;
}
}
}
// Cyclically traverse the key-Value Pair output
Foreach (KeyValuePair <char, int> item in dict)
{
Console. WriteLine ("number: {0} appears {1} Times. ", Item. Key, item. Value );
}
Console. ReadKey ();

 

It can be seen that a few simple lines of code are solved.

 

In addition, this solution completely solves the two problems encountered above.

I think this should be what the interviewer wants. (Khan... I don't know what the interview situation for my classmate is like ...)

 

Here, I thought of another interview question: "count the number of occurrences of each character in a string ".

This should be solved using the idea I first thought of. Wouldn't I have to write 26 case statements to judge? sweat .... I don't know if the interviewer will leave without seeing so much code... Obviously, this is not the best solution.

Use a generic set to solve the problem:

 

View Code

Class Program
{
Static void Main (string [] args)
{
// Calculate the number of times each character appears in the string (interview question ).
// "Welcome to China, beijing ",
// Case insensitive. Print "W2" "e 2" "o 3 "......

/* Train of Thought: 1. Convert all strings to lower-case format; otherwise, each string is regarded as one
* 2 a Dictionary <char, int> generic set is created based on the number of occurrences of each character as the value.
* 3 convert a string to a character array
* 4 cyclically traverse each character and add the set as the key. The corresponding value is initially 1
* 5 make a judgment before adding the key. Because the keys in the set cannot be repeated, make a judgment if the key already contains this character.
* This key is no longer added. Only the value of this key is + 1.
* 6 remove the space in the string char. isLetter (). If it is a letter, perform the following operations: 5
* 7 Summary: mainly application of generic Sets
*/

// Example:
// String sentences = "Welcome to China, beijing ";
Console. WriteLine ("enter a letter ");
String sentences = Console. ReadLine ();

// Convert all strings to lowercase
Sentences = sentences. ToLower ();
// Create a generic set
Dictionary <char, int> dict = new Dictionary <char, int> ();
// Convert the string into a character array
Char [] chs = sentences. ToCharArray ();

// Traverse each character
For (int I = 0; I <chs. Length; I ++)
{
// Determine whether it is a letter using the char method. If it is a letter, perform the following operations,
// Otherwise, do not operate
If (char. IsLetter (chs [I])
{
// If this key is not included, it is added to the set.
If (! Dict. ContainsKey (chs [I])
{
// Add each character to the corresponding key in the set. Its value is initially 1.
Dict. Add (chs [I], 1 );
}
Else
{
// Otherwise, only the corresponding value + 1 is of the int type.
// Dict [chs [I] = dict [chs [I] + 1;
Dict [chs [I] ++;
}
}


}
// Cyclically traverse the key values in the output set
Foreach (KeyValuePair <char, int> kv in dict)
{
Console. WriteLine ("letter: {0} appears {1} Times. ", Kv. Key, kv. Value );
}
Console. ReadKey ();
}
}

 

Similarly, the code is simple:

 

At this time, I suddenly thought of another situation:

The user enters a string of mixed letters and numbers, such as "ddeieiei4954jjfjdji383ddjeuut3003k"
Count the number of times each number or letter appears, and the number is in the front, the letter is in the back, the number and the letter are not required in order
For example, the number 4 appears twice.
Number 3 appears four times
.......
........
The letter d appears 5 times
...........

 

Of course, the simplest solution is to use a generic set ....

 

Let's end with a summary:

I personally think that the key to encountering a new problem is to train the train of thought and straighten out the ideas step by step. As our teacher said, I know what you want to do and how to do it, then write the code. Don't knock on the Code as soon as you come up, and you don't have a clear idea. In the end, there must be a lot of problems.

 

I hope this article will provide some small help to graduates like me who are looking for a job!

(I suddenly thought that the knowledge I learned in college was too simple and too deep to talk about. I am really helpless when looking for a job !!!)

 

Please give me some advice if you have any bad information!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.