class Solution { public: int integerReplacement(int n) { return integerReplacement(static_cast<long long>(n)); } private: int integerReplacement(long long n) { if (hash.count(n) > 0) { return hash[n]; } if (n == 1) { hash[1] = 0; return 0; } if (n % 2 == 0) { ...
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; } }...
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 1: Input:8Output:3Explanation:8 -> 4 -> 2 -> 1 Example 2: Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 ...
publicclassSolution {publicintintegerReplacement(intn) {if(n<1)return-1;intsteps = 0;while(n!=1){if(n%2==0){ n/= 2; }else{//We have: steps(2x) <= steps(2x-1) && steps(2x) <= steps(2x+1),i.e.,//for odd number, we go to (n-1) if (n-1)/2 is an even number...
Leetcode: Integer Replacement Given a positive integer n and you candooperations 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 neededforn to become 1?Example1:...
integer-replacement https://leetcode.com/problems/integer-replacement/ // 除了首位的1,其他的1需要2次操作,0需要1次操作。 // 所以尽量把1变成0 // 所以,3直接得出结果2, // 其他的,01->-1,11->+1 public class Solution { public int integerReplacement(int inn) {...
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...
*/ class Solution { public: string intToRoman(int num) { string s=""; while(num>=1000) { s+="M"; num=num-1000; } if(num>=900) { s+="CM"; num=num-900; } while(num>=500) { s+="D"; num=num-500; } if(num>=400) { s+="CD"; num=num-400; } while(num>=100)...
Reverse Integer LeetCode Java Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 public class Solution { public int reverse(int x) { if(x==Integer.MIN_VALUE) return 0; long result = 0; int i = 0; int temp = (x>0)?1:0; x = Math...
Reverse Integer LeetCode Java Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 public class Solution { public int reverse(int x) { if(x==Integer.MIN_VALUE) return 0; long result = 0; int i = 0; int temp = (x>0)?1:0; x = Math...