数学

7 Reverse Integer24.3%Easy

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

需要考虑溢出问题。
方法1:对于可能产生溢出的部分,做一个相反的操作,看看是否得到的是原值,如果不是,说明已经溢出了。
class Solution {
public:
    int reverse(int x) {
        //不需要考虑正负的区别
        int result=0;
        while(x)
        {
            int tail=x%10;
            x/=10;
            int newresult=result*10+tail;
            if((newresult-tail)/10!=result) return 0;
            result=newresult;
        }
        return result;
    }
};
方法2:结果使用一个较大的变量,使用标准库的int最大最小值处理。
class Solution {
public:
    int reverse(int x) {
        //不需要考虑正负的区别
        long long result=0;
        while(x)
        {
            result=result*10+x%10;
            x/=10;
        }
        if(result<std::numeric_limits<int>::min()||result>std::numeric_limits<int>::max()) return 0;
        return result;
    }
};

8. String to Integer (atoi)


9. Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.
确定一个数是否是回文数。不能使用额外的空间。
分析:通用的方法与7是类似的,只不过这里不需要全部翻转,只需要翻转一半即可。
class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0||(x!=0&&x%10==0)) return false;
        int res=0;
        while(x>res)//有些情况,这个循环是死循环,即末尾数字是零时,得出的结果是错的,或者是死循环
        {
            res=res*10+x%10;
            x/=10;
        }
        return (res==x)||(res/10==x);//翻转一半之后,如果是有奇数个,那么新的数多一位
    }
};

168 Excel Sheet Column Title25.8%Easy

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
class Solution {
public:
    string convertToTitle(int n) {
        return n==0?"":convertToTitle((n-1)/26)+(char)((n-1)%26+'A');
    }
};

628 Maximum Product of Three Numbers 45.1%Easy

给定一个整数数组,找到里面的三个数,使得三个数的乘积最大。
自己的分析:
如果只有三个数那么就是这三个数的乘积,如果超过三个数,排序,如果第一个数是负数第二个数不是负数,返回后三个数的乘积;如果前两个数是负数,比较后三个数和前两个数乘以最后一个数。
class Solution {
public:
    int maximumProduct(vector<int>& nums) {
        int n=nums.size();
        if(n==3) return nums[0]*nums[1]*nums[2];
        int result=0;
        sort(nums.begin(),nums.end());
        if(nums[0]>=0||(nums[0]<0&&nums[1]>=0))
            result=nums[n-1]*nums[n-2]*nums[n-3];
        else
        {
            result=(nums[0]*nums[1]>nums[n-2]*nums[n-3]?nums[0]*nums[1]:nums[n-2]*nums[n-3])*nums[n-1];
        }
        return result;
    }
};
13 Roman to Integer 45.5% Easy

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

将字符串转换为int数值

202 Happy Number40.5%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

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
不是幸运数的时候是一个循环,是幸运数的时候会有终点
我的思路:

class Solution {
public:
    bool isHappy(int n) {
        set<int> flag;
        if(!n) return false;
        flag.insert(n);
        while(n!=1)
        {
            n=dopow(n);
            if(flag.find(n)!=flag.end())
                return false;
            else if(n==1) return true;
            else flag.insert(n);
        }
        return true;
    }
    int dopow(int num){
        int sum=0;
        int temp=0;
        while(num)
        {
            temp=num%10;
            sum+=pow(temp,2);
            num/=10;
        }
        return sum;
    }
};

别人的思路, Floyd Cycle detection algorithm 类似于检测链表有无环一样,设置slow和fast,当slow和fast相等时,可能是套圈也可能是都走到终点了
int digitSquareSum(int n) {
    int sum = 0, tmp;
    while (n) {
        tmp = n % 10;
        sum += tmp * tmp;
        n /= 10;
    }
    return sum;
}

bool isHappy(int n) {
    int slow, fast;
    slow = fast = n;
    do {
        slow = digitSquareSum(slow);
        fast = digitSquareSum(fast);
        fast = digitSquareSum(fast);
    } while(slow != fast);
    if (slow == 1) return 1;
    else return 0;
}

204. Count Primes 计算质数
Count the number of prime numbers less than a non-negative number, n.
计算小于n的质数
我的思路:质数只能被1整除,将所有的已经求得的质数放到一个哈希表中,对于一个新的数,从sqrt(n)开始整除它,如果在哈希表中找不到,说明它也是质数。如果能够找到说明不是,另外寻找的数的最大值是sqrt(n)  超时
class Solution {
public:
    int countPrimes(int n) {
        if(n<=1) return 0;
        if(n<=4) return n-2;
        int sum=2;
        set<int> prime{2,3};
        for(int i=5;i<n;i++)
        {
            int j=sqrt(i);
            for(;j<i;j++)
            {
                if(i%j==0)
                {
                    if(prime.find(i/j)!=prime.end())
                        break;
                }
            }
            if(j==i) 
            {
                prime.insert(i);
                sum++;
            }
        }
        return sum;
    }
};
这种解法复杂度较高
另外一种别人的解法,效率更高。首先不考虑偶数,其次每一个奇数的等差数列都不是质数,从小的质数开始,能够保证后面的数只判断一次。
class Solution {
public:
    int countPrimes(int n) {
        if(n<=2) return 0;
        vector<bool> res(n,false);
        int sum=1;
        int upper=sqrt(n);
        for(int i=3;i<n;i+=2)
        {
            if(!res[i])
                sum++;
            if(i>upper) continue;
            for(int j=i*i;j<n;j+=i)
            {
                res[j]=true;
            }
        }
        return sum;
    }
};

231 Power of Two40.0%Easy

Given an integer, write a function to determine if it is a power of two.
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n<=0) return false;
        if(n==1) return true;
        while(n>2)
        {
            int factor=2;
                        while(factor<n)
            {
                if(n%factor!=0) return false;
                n/=factor;
                factor<<1;
            }
        }
        return true;
    }
};
好方法: 2的n次方的二进制只有一个1,这个数-1导致原来的1变成0,其他位变成1
class Solution {
public:
    bool isPowerOfTwo(int n) {
     if(n<=0) return false;
        return !(n&(n-1));
    }
};

326Power of Three40.1%Easy

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0) return false;
        int m=pow(3,19);
        if(n<=0||n>m) return false;
        return m%n==0;
    }
};


342. Power of Four


Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

class Solution {
public:
    bool isPowerOfFour(int num) {
        return (num&(num-1))==0&&(num-1)%3==0;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值