Incorrect output for large input


  • 0
    N
    class Solution {
    public:
       vector<int> getRow(int rowIndex) {
        vector<int> result;
        if(rowIndex>=0)
        {
            int n=(rowIndex+1)/2;
            int temp=1;
            double up=(double)rowIndex;
            double down=1;
            int i=1;
            if(rowIndex%2==1)i++;
            result.push_back(1);
            if(n>0)
            {
                while(i<=n&&up>0)
                {
    
                    temp*=(up/down);
                    result.push_back(temp);
                    down++;
                    up--;
                    i++;
                }
            for(i=1;i<=n;i++){
                        result.push_back(result[n-i]);
                    }
            } 
        }
        return result;
    }
    };

  • 1
    V

    Change the data type of variable temp to double from int, as integer gets rounded off after evaluation of the expression temp = temp * (up/down)

       class Solution {
        public:
           vector<int> getRow(int rowIndex) {
            vector<int> result;
            if(rowIndex>=0)
            {
                int n=(rowIndex+1)/2;
                double temp=1;
                double up=(double)rowIndex;
                double down=1;
                int i=1;
                if(rowIndex%2==1)i++;
                result.push_back(1);
                if(n>0)
                {
                    while(i<=n&&up>0)
                    {
        
                        temp*=(up/down);
                        result.push_back(temp);
                        down++;
                        up--;
                        i++;
                    }
                for(i=1;i<=n;i++){
                            result.push_back(result[n-i]);
                        }
                } 
            }
            return result;
        }
        };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.