网易笔试算法题
一个数列:1,12,123,...12345678910,1234567891011...,计算这个数列的第l个到第r个(包含端点)有多少个数可以被3整除。
输入描述:输入包括两个整数 l 和 r (1 <= l <= r <= 1e9),表示要求解的区间两端。
输出描述:输出一个整数,表示区间内能被 3 整除的数字个数。
示例:l = 2, r = 5,输出3.
解答:能被3整除满足的性质为:所有位上之和是3的倍数。
通过观察数列,能发现该数列满足被3整除其实是按照0-1-1-0-1-1无限循环,即:1不能被3整除,12能被3整除,123能被3整除,1234不能被3整除,12345能被3整除,123456能被3整除,......
代码:
(1)自己写的:
import java.util.*;
public class ReorderOddEven {
public static void main(String[] args){
long startTime = System.currentTimeMillis(); //获取当前时间
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt()){
int l = scan.nextInt();
int r = scan.nextInt();
int count1 = 0;
int count2 = 0;
if(l > r){
System.out.println(count1);
}
if(l%3 != 0){
count1 = (l/3)*2;
}
else{
count1 = (l/3)*2-1;
}
if(r%3 != 0){
count2 = (r/3)*2+(r%3)-1;
}
else{
count2 = (r/3)*2;
}
System.out.println(count2-count1);
}
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:"+(endTime-startTime)+"ms");
}
}
(2)大神写的
import java.util.*;
public class shuLie {
public static int calc(int x){
return (x+2)/3;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNextInt()){
int l = scan.nextInt();
int r = scan.nextInt();
System.out.println(r-l+1-(calc(r)-calc(l-1)));
}
}
}