class Solution {
public:
string addBinary(string a, string b) {
string ans;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int n = max(a.size(), b.size()), carry = 0;
for (size_t i = 0; i < n; ++i) {
carry += i < a.size() ? (a.at(i) == '1') : 0;
carry += i < b.size() ? (b.at(i) == '1') : 0;
ans.push_back((carry % 2) ? '1' : '0');
carry /= 2;
}
if (carry) {
ans.push_back('1');
}
reverse(ans.begin(), ans.end());
return ans;
}
};
class Solution {
private:
static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int rows = matrix.size(), columns = matrix[0].size();
vector<vector<bool>> visited(rows, vector<bool>(columns));
int total = rows * columns;
vector<int> order(total);
int row = 0, column = 0;
int directionIndex = 0;
for (int i = 0; i < total; i++) {
order[i] = matrix[row][column];
visited[row][column] = true;
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
};
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int x = 0, y = 0, di = 0;
unordered_set<pair<int, int>, pair_hash> obstacleSet;
for (vector<int> obstacle: obstacles)
obstacleSet.insert(make_pair(obstacle[0], obstacle[1]));
int ans = 0;
for (int cmd: commands) {
if (cmd == -2)
di = (di + 3) % 4;
else if (cmd == -1)
di = (di + 1) % 4;
else {
for (int k = 0; k < cmd; ++k) {
int nx = x + dx[di];
int ny = y + dy[di];
if (obstacleSet.find(make_pair(nx, ny)) == obstacleSet.end()) {
x = nx;
y = ny;
ans = max(ans, x*x + y*y);
}
}
}
}
return ans;
}
private:
struct pair_hash
{
template <class T1, class T2>
std::size_t operator () (std::pair<T1, T2> const &pair) const
{
std::size_t h1 = std::hash<T1>()(pair.first);
std::size_t h2 = std::hash<T2>()(pair.second);
return h1 ^ h2;
}
};
};