Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 6, 8
are ugly while 14
is not ugly since it includes another prime factor 7
.
Note:
1
is typically treated as an ugly number.- Input is within the 32-bit signed integer range.
class Solution {
public:
bool isUgly(int num) {
if(num<=0) return false;
if(num==1) return true;
int temp=num;
int prime[3]={2,3,5};
for(int i=0;i<3;i++)
{
while(num%prime[i]==0)
num/=prime[i];
}
if(num==1) return true;
return false;
}
};
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number, and n does not exceed 1690.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
class Solution {
public:
int nthUglyNumber(int n) {
if(n<=6) return n;
vector<int>v(n+1);
v[1]=1;
int t2=1,t3=1,t5=1;
for(int i=2;i<=n;i++)
{
v[i]=min(v[t2]*2,min(v[t3]*3,v[t5]*5));
if(v[i]==v[t2]*2) t2++;
if(v[i]==v[t3]*3) t3++;
if(v[i]==v[t5]*5) t5++;
}
return v[n];
}
};
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
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
证明:
判断某个数是否是开心数,很容易想到:如果各位上数的平方和到达1前出现循环,则该数必定不是开心数,因为它将无限循环。
因此,只要我们能发现循环在出现1之前,这个数一定不是开心数。
但是还需要证明:不开心数是不是一定存在循环节?不然与上述结论相悖,因为可能存在不开心数是没有循环节的。
不开心数是一定存在循环节的。一个n位的数,n个位都是9的情况,则平方和的区间为[1,n*pow(9,2)];如果平方和在这个区间都只出现了一次,那么下一次将导致重复,所以一定存在循环节。
该题运用到了Floyd循环侦查判断的特点。
class Solution {
public:
bool isHappy(int n) {
int a=n,b=n;
do{
a=work(a);
b=work(b);
b=work(b);
if(b==1) return true;
}while(a!=b);
if(a==1) return true;
else return false;
}
private:
int work(int n)
{
int res=0;
while(n)
{
res+=(n%10)*(n%10);
n/=10;
}
return res;
}
};
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?
存在公式:https://en.wikipedia.org/wiki/Digital_root#Congruence_formula
写出前十几个数后将会发现规律:
INPUT 0 1 2 3 4 5 6 7 8 9 10 11 12 13……
OUTPUT 0 1 2 3 4 5 6 7 8 9 1 2 3 4……
class Solution {
public:
int addDigits(int num) {
return 1+(num-1)%9;
}
};