258 . Add Digits
Easy
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
4ms:
public int addDigits(int num) {
char[] cabin = Integer.valueOf(num).toString().toCharArray();
while(cabin.length>1){
int sum=0;
for(char x:cabin){
sum+=x-'0';
}
cabin = Integer.valueOf(sum).toString().toCharArray();
}
return cabin[0]-'0';
}
2ms:
public int addDigits(int num) {
num--;
while(num>=9){
num %=9;
}
return ++num;
}
2ms:
public int addDigits(int num) {
return (num - 1) % 9 + 1;
}
202 . Happy Number
Easy
Write an algorithm to determine if a number is “happy”.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1*1 + 9*9 = 82
8*8 + 2*2 = 68
6*6 + 8*8 = 100
1*1 + 0*0 + 0*0 = 1
8ms:
public boolean isHappy(int n) {
Set<Integer> se = new HashSet<Integer>();
while(n!=1){
n = getH(n);
if(se.contains(n))
return false;
se.add(n);
}
return true;
}
private int getH(int n){
int c = 0;
while(n!=0){
c+=(n%10)*(n%10);
n /= 10;
}
return c;
}