classSolution {public:intintegerReplacement(intn) {longlongt =n;intcnt =0;while(t >1) {++cnt;if(t &1) {if((t &2) && (t !=3)) ++t;else--t; }else{ t>>=1; } }returncnt; } }; 参考资料: https://discuss.leetcode.com/topic/58655/0ms-cpp-solution LeetCode All in One 题目讲解汇总(持续更新中...)
Code classSolution{public:intintegerReplacement(intn){if(n ==1)return0;if(n ==2)return1;if(n ==3)return2;if(n == INT_MAX)return32;if(!(n &1))returnintegerReplacement(n /2) +1;else{if((n +1) %4==0)returnintegerReplacement(n +1) +1;elsereturnintegerReplacement(n -1) +1; ...
Otherwise, incrementn. 1publicintintegerReplacement(intn) {2intc = 0;3while(n != 1) {4if((n & 1) == 0) {5n >>>= 1;6}elseif(n == 3 || Integer.bitCount(n + 1) > Integer.bitCount(n - 1)) {7--n;8}else{9++n;10}11++c;12}13returnc;14} 1. 2. 3. 4. 5. 6....
class Solution { public: int integerReplacement(int n) { long long t = n; int cnt = 0; while (t > 1) { ++cnt; if (t & 1) { if ((t & 2) && (t != 3)) ++t; else --t; } else { t >>= 1; } } return cnt; } }; 参考资料: https://discuss.leetcode.com/topic...
packageleetcodefuncintegerReplacement(nint)int{res:=0forn>1{if(n&1)==0{// 判断是否是偶数n>>=1}elseif(n+1)%4==0&&n!=3{// 末尾 2 位为 11n++}else{// 末尾 2 位为 01n--}res++}returnres} 1. 2. 3. 4. 5. 6. 7. ...
[LeetCode] Integer Replacement 整数替换 Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of replacements needed for n to become 1? Example...
[LeetCode] Integer Replacement 整数替换 Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of replacements needed for n to become 1? Example...
Integer to Roman LeetCode(java实现) Integerto Roman LeetCode(java实现) SPRING MVC3.2案例讲解--SPRING MVC3的POJO赋值 ConvertController { // http://127.0.0.1:8010/convert/primitive?value=3@RequestMapping("primitive") public @ResponseBody Stringprimitive(@RequestParamIntegervalue) { return "Converted ...
0424-longest-repeating-character-replacement.cpp 0435-non-overlapping-intervals.cpp 0438-find-all-anagrams-in-a-string.cpp 0441-arranging-coins.cpp 0448-find-all-numbers-disappeared-in-an-array.cpp 0450-delete-node-in-a-bst.cpp 0456-132-pattern.cpp 0463-island-perimeter.cpp 0473-matchsticks-to-...
publicintintegerReplacement(intn){intc=0;while(n!=1){if((n&1)==0){n>>>=1;}elseif(n==3||Integer.bitCount(n+1)>Integer.bitCount(n-1)){--n;}else{++n;}++c;}returnc;} Of course, doingbitCounton every iteration is not the best way. It is enough to examine the last two dig...