[LeetCode] Fraction to Recurring Decimal,leetcoderecurring

來源:互聯網
上載者:User

[LeetCode] Fraction to Recurring Decimal,leetcoderecurring

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".


這題實現起來還是比較麻煩的,主要還要考慮負數的輸入情況,特別是-2147483648這樣的整數型的邊界值。最簡單的方法就是先把所有的輸入全部轉換為長整型的正數。

另外,由於要記錄小數裡迴圈的部分,所以還需要用到一個Map去記錄小數點的每位和對應的餘數值。如果碰到的同樣的餘數值,那麼說明遇到了開始迴圈的部分了。

public String fractionToDecimal(int numerator, int denominator) {long longNumerator = Math.abs((long) numerator);long longDenominator = Math.abs((long) denominator);StringBuilder sb = new StringBuilder();if ((long) numerator * denominator < 0) sb.append("-");sb.append(longNumerator / longDenominator);long remainder = longNumerator % longDenominator;if (remainder == 0) return sb.toString();sb.append(".");StringBuilder fracSb = new StringBuilder();Map<Long, Integer> map = new HashMap<Long, Integer>();int index = 0;while (remainder != 0) {remainder *= 10;long nextRemainder = remainder % longDenominator;// If repeated part occurs.if (map.containsKey(remainder)) {fracSb.insert(map.get(remainder), "(");fracSb.append(")");break;}map.put(remainder, index++);fracSb.append(remainder / longDenominator);remainder = nextRemainder;}sb.append(fracSb);return sb.toString();}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.