-
題目描述:給你一個單鏈表的引用結點 head。鏈表中每個結點的值不是 0 就是 1。已知此鏈表是一個整數數字的二進制表示形式。
請你返回該鏈表所表示數字的 十進制值 。
-
示例 1:
輸入:head = [1,0,1]
輸出:5
解釋:二進制數 (101) 轉化爲十進制數 (5) -
示例 2:
輸入:head = [0]
輸出:0 -
示例 3:
輸入:head = [1]
輸出:1 -
示例 4:
輸入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
輸出:18880 -
示例 5:
輸入:head = [0,0]
輸出:0 -
提示:
鏈表不爲空。
鏈表的結點總數不超過 30。
每個結點的值不是 0 就是 1。 -
我的題解:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public int getDecimalValue(ListNode head) { ListNode p = head; StringBuffer sb = new StringBuffer(); while(p!=null) { if(p!=null) { sb.append(p.val); } p = p.next; } return Integer.parseInt(sb.toString(),2); } }
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。