用 C++到達我們數字


假設您站在無限數軸上的位置 0。現在,目標是位置 target。每次移動,您都可以向左側或右側移動。在第 n 次移動(從 1 開始)中,您需要走 n 步。我們必須找出到達目的地所需的最小步數。因此,如果輸入為 target = 3,則我們需要 2 步。從 0 到 1,從 1 到 3。

要解決這個問題,我們將按照以下步驟進行 -

  • target := |target|, cnt := 0
  • 在 target > 0 時,
    • cnt 減 1
    • target := target –cnt
  • 如果 target 為偶數,則返回 cnt,否則返回 cnt + 1 + cnt 模 2

讓我們瞭解一下以下實現以獲得更好的理解 -

示例

 實戰演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int reachNumber(int target) {
      target = abs(target);
      int cnt = 0;
      while(target > 0){
         target -= ++cnt;
      }
      return target % 2 == 0? cnt : cnt + 1 + cnt % 2;
   }
};
main(){
   Solution ob;
   cout << (ob.reachNumber(3));
}

輸入

3

輸出

2

更新於: 04-May-2020

175 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.