c# - Find Numbers that Start with 31 and End with 21 on the given Interval -


i looking function (with integer / math operation, instead of string) determine whether input number starts 31 , end 21.

for example, given array of integers below:

{ 341521, 513135, 434632, 312321, 315364, 312421 }

the function should return 312321 , 312421.

i still don't have completed, here's have far (c#):

public bool isvalidid(int input) {     var result = input >= 310000 && input < 320000;      if (result)     {         // check ending 21, maybe         // var endwith = (double) ((input / 21) / 100);         // check if endwith has decimal..     }      return result; } 

this acheived quite using strings using startswith , endswith if dont want use strings @ can keep find digit in number using math.log10 , math.pow functions. try explain use of these functions mathematics nomenclature rusty i'm fail horribly. commented code explain uses of variables.

public static void main(string [] args) {     int [] checks = new int[] { 341521, 513135, 434632, 312321, 315364, 312421 };     for(int check : checks) {         system.out.println(check + " " + startswithendswith(check, 31, 21));     } }  public static boolean startswithendswith(int value, int startwithnumber, int endswithnumber) {     // number of digits each of our inputs     int numvaluedigits = (int) math.log10(value);     int numstartsdigits = (int) math.log10(startwithnumber);     int numendsdigits = (int) math.log10(endswithnumber);      // if value doesnt have many digits either our starting or ending numbers impossible true     if(numvaluedigits < numstartsdigits || numvaluedigits < numendsdigits) {         return false;     }      // each of our startwithnumber digits check if number in value matches corrisponding number in startswithnumber     for(int i=0;i<=numstartsdigits;i++) {         if(getdigitat(value, numvaluedigits-i) != getdigitat(startwithnumber, numstartsdigits-i)) {             return false;         }     }      // each of our endswithnumber digits check if number in value matches corrisponding number in endswithnumber     for(int i=0;i<=numendsdigits;i++) {         if(getdigitat(value, i) != getdigitat(endswithnumber, i)) {             return false;         }     }      // nothing failed therefore valid     return true; }  /**  * returns digit @ specified location, starting @ 0 1's place. returns 0 if location higher number  * @param num  * @param location 0<=location<=9  * @return  */ private static int getdigitat(int num, int location) {     // divide our number 10^location make digit @ location     // in 1's position, modulus 10 extract digit     return (int) (num/math.pow(10, location)) % 10; } 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -