How to find what range a number is in
I have folders named like this:
"1-500"
"501-1000"
"1001-1500"
"1501-2000"
"2501-3000"
etc....
Given an Id such as 1777
how can I find the name of the folder it belongs in?
I am using Java, 开发者_如何学Cbut your answer can be pseudocode.
Thanks!
Here is how:
// Folder 0: 1-500
// Folder 1: 501-1000
// Folder 2: 1001-1500
// ...
int n = 1777;
int folder = (n-1) / 500;
System.out.printf("%d belongs to folder %d - %d",
n, folder * 500 + 1, (folder+1) * 500);
Output:
1777 belongs to folder 1501 - 2000
The integer division will take care of the "flooring" required to get the right folder-index. Be careful to include the - 1
. Otherwise, n = 500
will end up in group 1 (instead of 0).
int n = 1777;
int temp = ((n / 500) * 500) + 1 ;
if(temp > n && n !=0){
temp-=500;
}
String result = "" + temp + " - "+ (temp + 499);
System.out.println(result);
- Here is working IDE One demo
If you want a more generic method, here it goes (based on the https://stackoverflow.com/users/276052/aioobe's solution):
public static void main(String[] args) {
for (int i = 1; i <= 3000; i++) {
System.out.println(i + "\t" + getRange(i, 1000));
}
}
private static String getRange(int id, int step) {
int x = ((id - 1) / step);
return (x * step + 1) + "-" + ((x + 1) * step);
}
foreach ( folder in folders )
[from, to] = split( folder.name, "-" )
if ( id < from || id > to )
continue
// found the right folder.
"1-500" -> folder 0
"501-1000" -> folder 1
"1001-1500" -> folder 2
...
Take (1777 - 1) / 500 using integer division to get the folder number.
Just iterate over your folders, split the name by "-", parse two numbers and check if your number is in range:)
You could just use a few cases, where you'd check if it's between specified values, like: 10 < x && x < 20
If it's always going to be a range of five hundred you can do this:
for(int i = 0; i < Integer.MAX_VALUE; i++){
if(i*500+1 >= x && (i+1)*500 < x){
System.out.println("X is between " + (i*500 + 1) + " and " + ((i+1) * 500));
}
}
Where the variable 'x' is the id.
If you have to use the folder names, you will need to read the folders names, split on the '-' and then attempt to parse them into integers and use that instead of my for loop.
Here is your function :
public String folderName(int num)
{
StringBuilder sb = new StringBuilder();
sb.append(1+(num-1)/500).append('-').append((1+((num-1)/500))*500);
return sb.toString();
}
精彩评论