封校生活============
目录
1.快乐数(链表的思想)
202. 快乐数 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/happy-number/
题目及要求:
解题思路:
①分为两种情况:a.结果是1(即是快乐数)
b.是循环的往复的情况(死循环,想到环状链表)
②环状链表中设置一快一慢的两个指针(slow一次一步,fast一次两步)
③若slow与fast相遇,那么说明是死循环,即非快乐数
④若fast==1,快的到达了1则表明慢的必然也会到达1,即为快乐数
代码如下:
class Solution { public int sqartNum(int n){ int m=0; while(n>0){ m+=(n%10)*(n%10); n/=10; } return m; } public boolean isHappy(int n) { int slow=n; int fast=sqartNum(n); while(slow!=fast&&fast!=1){ slow=sqartNum(slow); fast=sqartNum(sqartNum(fast)); } return fast==1; } }
2.丑数
263. 丑数 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/ugly-number/comments/
题目及要求:
解题思路:
①将含有某个质因数转化成n%某个质因数=0;
②利用递归将问题进行转换
代码如下:
class Solution { public boolean isUgly(int n) { if(n==0)return false; if(n==1)return true; if(n%2==0){ return isUgly(n/2); }if(n%3==0){ return isUgly(n/3); }if(n%5==0){ return isUgly(n/5); }return false; } }
3.各位相加
258. 各位相加 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/add-digits/submissions/
题目及要求:
解题思路:
①要知道个位上的数字如何求;n%10;
②要知道怎么将n位数转变为n-1位数,n/10;
代码如下:
class Solution { public int addDigits(int num) { while(num/10>=1){ int m=0; m+=num/10+num%10; num=m; }return num; } }
感谢观看~