1、编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直
到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19 输出: true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
/*
*解释一下:每一个非快乐数总会算到89,所以只要算出了89,这个数一定不是快乐数
*/
public class Test{
public boolean solution(int n){
while(n!=1){
int flag = getNext(n);
if(flag == 1){
return true;
}
else{
n = flag;
if(n == 89){
return false;
}
}
}
return true;
}
public int getNext(int n){
int result = 0;
while(n!=0){
result = result + ((n%10)*(n%10));
n = n/10;
}
return result;
}
public static void main(String[] args){
Test test = new Test();
System.out.println(test.solution(20));
}
}
2、10个人报数,报到3的人淘汰掉,最后剩下的一个人是第几个人
public class Test{
public static void main(String[] args) {
int[] people = new int[10];
//给每个人编号
for(int i = 0;i<people.length;i++){
people[i] = i+1;
}
//报数标志
int flag = 0;
//退出人数
int quitPeople = 0;
//计数器
int i = 0;
while(quitPeople < (people.length-1)){
if(people[i] != 0){
//这个人还在
flag++;
}
if(flag == 3){
people[i] = 0;
flag = 0;
quitPeople++;
}
//轮流
i++;
if(i == 10){
i = 0;
}
}
for(i = 0;i<people.length;i++){
if(people[i]!=0){
System.out.println(people[i]);
}
}
}
}
3、给定一个英文字符串,
- 写一段代码找出字符串中首先出现三次的英文字母。 输入描述:输入数据一个
- 字符串,包括字母,数字 输出描述:输出首先出现三次的那个英文字符
- 示例: 输入: Have you ever gone shopping
- and 输出: e
public class Test {
public static void main(String[] args){
String str = "Have you ever gone shopping";
System.out.println(firstThree(str));
}
public static char firstThree(String str){
char[] temp = str.toCharArray();
int[] hash = new int[256];
for(int i = 0;i < temp.length;i++){
char c = temp[i];
if((c>'A'&&c<'Z')||(c>'a'&&c<'z')){
hash[c]++;
if(hash[c] == 3){
return c;
}
}
}
return '0';
}
}