A number spiral is an infinite grid whose upper-left square has the number 1. Here are the first five layers of the spiral:
Your task is to find out the number in row y and column x.
Example:
Input: x = 2, y = 3
Output: 8
Approach
C++
#include <bits/stdc++.h>using namespace std;void numberSpiral(long long int x, long long int y){if (x >= y){if (x % 2 == 0){long long int r = x * x;cout << r - y + 1 << "\n";}else{long long int r = (x - 1) * (x - 1) + 1;cout << r + y - 1 << "\n";}}else if (x < y){if (y % 2 == 1){long long int r = y * y;cout << r - x + 1 << "\n";}else{long long int r = (y - 1) * (y - 1) + 1;cout << r + x - 1 << "\n";}}}int main(){long long int x = 2, y = 3;numberSpiral(x, y);return 0;}
No comments:
Post a Comment