1. 程式人生 > 其它 >leetcode367. 有效的完全平方數(二分,牛頓迭代,因數法)

leetcode367. 有效的完全平方數(二分,牛頓迭代,因數法)

ִ����ʱ��
0 ms
, ������ C �ύ�л�����
100.00%
���û�
�ڴ����ģ�
5.4 MB
, ������ C �ύ�л�����
41.47%
���û�

��������ȭ����

ʹ�� bulid-in library

bool isPerfectSquare(int num)
{
    return (int)sqrt(num) * (int)sqrt(num) == num ? 1 : 0;
}

���ַ�

�������ʹ���� long ��, ���� num/mid �� mid �Ƚ��������ж�,������ mid*mid ���,���������һ���������������(����ʹ�� "5" ���в���), ����"5"�����һ������ mid=2,tmp=2,������Ҫ�ж��Ƿ���Գ���

bool isPerfectSquare_Binary(int num) //Binary,���ַ�
{
    int bottom = 1, top = num;
    while (bottom <= top)
    {
        int mid = (top - bottom) / 2 + bottom;
        int tmp = num / mid;

        if (tmp > mid)
            bottom = mid + 1;
        else if (tmp < mid)
            top = mid - 1;
        else
        {
            if (num % mid == 0)
                return 1;
            bottom = mid + 1;
        }
    }
    return 0;
}

�����ӷ�

ֻ���� ��num

bool isPerfectSquare_EnumerateFactor(int num) //�ҳ�һ��num������,����i*i=num
{
    for (int i = 1; i <= num / i; i++)
    {
        if (num == i * i)
            return 1;
    }
    return 0;
}

ţ�ٵ�����

������ѧ������
leetcode �ٷ����

bool isPerfectSquare_NewtonIteration(int num) //newton iteration method,ţ�ٵ���
{
    double x = num;
    double tmp = 1 + x;
    while (tmp - x > 1e-6)
    {
        tmp = x;
        double res = (x + num / x) / 2;
        x = res;
    }
    return (int)x * (int)x == num;
}