I'm having trouble thinking of a solution to this problem that doesn't involve a loop. Basically, if something is greater than some arbitrary number, it loops around. Let's say 64 is the number.
0 => 0
32 => 32
64 => 64
96 => 32
128 => 64
160 => 32
192 => 64
Et cetera.
The way I'm currently doing it involves a while loop that checks to see if the value is over 64 and if it is, subtract 64 from it. Is there another way to do it that doesn't involve loops?
I'm using C# WinFo开发者_如何学运维rms.
Mod the value by 64, it's an O(1) operation. Like this:
int number;
// number is initialized
number %= 64;
public static int filterNumber(int x, int arbitraryNumber) {
if (x < arbitraryNumber) {
return x;
}
int result = x % arbitraryNumber;
if (result == 0) {
return arbitraryNumber;
}
return result;
}
Modulo alone won't help in the case of equally divisible by 64.
if (number == 0)
return 0;
var mod = number % 64;
return (mod == 0) ? 64 : mod;
return n == 0 ? 0 :
n % 64 == 0 ? 64 :
n % 32 == 0 ? 32 :
-1; // you have not specified this case in your examples!
精彩评论