top of page

Daily Coding Problem #8

Writer's picture: Mischievous_FaceMischievous_Face

// Given a sorted list of integers, square the elements and give the output in sorted order.

// For example, given[-9, -2, 0, 2, 3], return[0, 4, 4, 9, 81].


#include <list>

#include <iostream>


using namespace std;


list<int> squareList(list<int> numbers)

{

unsigned ogSzize = numbers.size();


for (unsigned i = 0; i < ogSzize; ++i)

{

int square = numbers.front() * numbers.front();

numbers.pop_front();

numbers.push_back(square);

}


// Im dodging the question a bit here by using the STL

// but this is the fastest way I could see finishing the problem

numbers.sort();

return numbers;

}


// the problem says that we have a "list" despite using array notation

// I assumed the list was literal and used and STL linked list

int main()

{

list<int> input = list<int>();

//[-9, -2, 0, 2, 3]

input.push_back(-9);

input.push_back(-2);

input.push_back(0);

input.push_back(2);

input.push_back(3);


auto result = squareList(input);


// should see [0, 4, 4, 9, 81]

unsigned its = result.size();

for (unsigned i = 0; i < its; ++i)

{

cout << result.front() << endl;

result.pop_front();

}


return 0;

}

10 views0 comments

Recent Posts

See All

Comments


© 2020 Josh Painter

bottom of page