202. 快樂數
class Solution {
public boolean isHappy(int n) {
int slow = n;
int fast = squareSum(n);
while(fast!=slow){
slow = squareSum(slow);
fast = squareSum(squareSum(fast));
}
return fast ==1;
}
private int squareSum(int n){
int sum = 0;
while(n>0){
int digit = n%10;
sum += digit*digit;
n = n/10;
}
return sum;
}
}
面試題67. 把字符串轉換成整數
class Solution {
public int strToInt(String str) {
char[] c = str.trim().toCharArray();
if(c.length == 0) return 0;
long res = 0;
int i = 1, sign = 1;
if(c[0] == '-') sign = -1;
else if(c[0] != '+') i = 0;
for(int j = i; j < c.length; j++) {
if(c[j] < '0' || c[j] > '9') break;
res = res * 10 + (c[j] - '0');
if(res > Integer.MAX_VALUE) return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
return sign * (int)res;
}
}
你知道的越多,你不知道的越多。
有道無術,術尚可求,有術無道,止於術。
如有其它問題,歡迎大家留言,我們一起討論,一起學習,一起進步