幸运数
来源:互联网 发布:网络规划设计师通过率 编辑:程序博客网 时间:2024/05/13 12:17
这是一个学长今年去参加面试的题目:
描述:小雅同学认为6.8是他的幸运数字,而其他数字不是,一个幸运数是指在十进制表示下
只含有幸运数字的数。给定一个区间(a,b),请使用java程序编写一个函数,
返回a和b之间幸运数的个数。可以使用伪代码
输入 : a,b a的范围在1-1000 000 000,b的范围为a到 1 000 000 000之间
输出 : 返回a,b之间的幸运数个数
如6.66.88,688为幸运数字
简单分析一下:题目要求输入一个十进制整数,判断是否是只有6和8,范围给定如上,且a<b
a,b的范围是可以用int 类型存储的(Integer.MAX_VALUE = 2 147 483 647)
如果用了long 可能就减分了。
分析题目知道了我们至少可以使用两种方法做出来:
1,使用字符串
2,直接使用整形数据
其中第二种方法比较麻烦
下面是两种方法的代码
import java.util.Scanner;public class XYInterview { public static void main(String[] args) {//System.out.println(Integer.MAX_VALUE);Scanner sc = new Scanner(System.in);while(sc.hasNext()){int a = sc.nextInt();int b = sc.nextInt();int count=0;for(int i=a+1; i<b; i++){String str = ""+i;boolean isLuck=true;for(int j=0;j<str.length();j++){char ch = str.charAt(j);if(ch=='6' || ch=='8'){continue;}else{isLuck=false;break;}}if(isLuck){System.out.println(">>"+i);count++;}}System.out.println(count);} }}
import java.util.Scanner;public class XYInterview2 { public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){int a = sc.nextInt();int b = sc.nextInt();int count=0;for(int i=a+1; i<b; i++){int t=i;boolean boo=true;while(t>10){int x=t%10;if(x!=6 && x!=8){boo=false;break;}t = t/10;}if(boo==false){continue;}if(t==6 || t==8){count++;System.out.println(">>"+i);}}System.out.println(count);} }}