题解 | #反转数字#
反转数字
https://www.nowcoder.com/practice/1a3de8b83d12437aa05694b90e02f47a
using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param x int整型 * @return int整型 */ public int reverse (int x) { // write code here int nFlag = x >= 0 ? 1 : -1; string strX = x.ToString(); strX = nFlag < 0 ? strX.Replace("-", "") : strX; string strRX = string.Empty; for (int nIndex = 0; nIndex < strX.Length; nIndex++) strRX = strX[nIndex].ToString() + strRX; int nRtn = 0; string strLQ = (Math.Pow(2, 31)).ToString(); string strRQ = (Math.Pow(2, 31) - 1).ToString(); bool bL = strRX.Length > strLQ.Length || ((strRX.Length == strLQ.Length) && string.Compare(strRX, strLQ) > 0); bool bR = strRX.Length > strRQ.Length || ((strRX.Length == strRQ.Length) && string.Compare(strRX, strRQ) > 0); if (bL || bR) return 0; for (int nIndex = strX.Length - 1; nIndex >= 0; nIndex--) nRtn += Convert.ToInt32(strX[nIndex].ToString()) * (int)Math.Pow(10, nIndex); return nFlag * nRtn; } }