I have some int value its name is number. I have other int value its name is x. I want to know is x exist in number or not. Currently I convert number to string() and use string.Contain(x) method. I think this is not a good way, it does boxing and performance is hurt.
Are there a better way to do this?
Additional information:
number may be one or more digit, for example, 12345. x is always one digit.
That’s not a bad method. The only alternative I can think of is something using repeated divisions and modulus operators which may well be slower due to the quantity of those operations.
I’d stick with what you have unless there’s a serious performance problem.
Based on your additional information:
I would opt for the following (pseudo-code):
The first
ifis required since you don’t enter thewhileif you pass in anumberof0and you still have to catch the case where bothnumberanddigitare0.Otherwise, you just continue to check the least significant digit of
numberagainstdigit, and dividenumberby 10 each time.If a match is found before
numberreaches zero, it contains the digit. Otherwise it doesn’t.This will probably be faster than your string solution, since it will have to do similar operations to create the string from the integer and then do the string compare on top of that.
But, as with all optimisations, measure, don’t guess!
And, now that I have access to my VS2008 development box, her’s some C# code for it: