C#练习题答案: 简单有趣#140:圆斩【难度:2级】--景越C#经典编程题库,1000道C#基础练习题等你来挑战

mac2022-06-30  111

简单有趣#140:圆斩【难度:2级】:

答案1:

namespace myjinxin { public class Kata { public int CircleSlash( int n ) { return 2*( n - HighestOneBit( n ) ) + 1; } private int HighestOneBit( int n ) { n |= ( n >> 1 ); n |= ( n >> 2 ); n |= ( n >> 4 ); n |= ( n >> 8 ); n |= ( n >> 16 ); return n - ( n >> 1 ); } } }

答案2:

namespace myjinxin { using System; public class Kata { public int CircleSlash(int n) { int lo = (int)Math.Log(n, 2); int lop = (int)Math.Pow(2, lo); int diff = (n - lop) * 2 + 1; return diff; } } }

答案3:

namespace myjinxin { using System; public class Kata { public int CircleSlash(int n) => 2 * (n - (int)Math.Pow(2, Convert.ToString(n, 2).Length - 1)) + 1; } }

答案4:

namespace myjinxin { using System; public class Kata { public int CircleSlash(int n) => (int) (2 * (n - Math.Pow(2, Math.Floor(Math.Log(n, 2)))) + 1);//a(n) = 2*(n - 2^floor(log2(n))) + 1 } }

答案5:

namespace myjinxin { using System; public class Kata { public int CircleSlash(int n){ return 2 * (n - (int)Math.Pow(2, Convert.ToString(n, 2).Length - 1)) + 1; } } }

答案6:

namespace myjinxin { using System; public class Kata { public int CircleSlash(int n) { int min = 1; int max = n; int stepCountBetween = 1; bool firstMemberhassword = true; // the first or the last has the sword after one loop while (min != max) { if (((max - min) / stepCountBetween) % 2 == 0) { if (firstMemberhassword) { firstMemberhassword = false; } else if (!firstMemberhassword) { min += stepCountBetween; max -= stepCountBetween; firstMemberhassword = true; } } else if (((max - min) / stepCountBetween) % 2 != 0) { if (firstMemberhassword) { max -= stepCountBetween; } else if (!firstMemberhassword) { min += stepCountBetween; } } stepCountBetween *= 2; } return min; } } }

答案7:

namespace myjinxin { using System; public class Kata { public int CircleSlash(int n) => (n - (1 << (int)Math.Log(n, 2))) << 1 | 1; } }

答案8:

namespace myjinxin { using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; public class Kata { public int CircleSlash(int n){ return (int)(n-Math.Pow(2,Math.Floor(Math.Log(n,2))))*2+1; } } }
最新回复(0)