[ 命名建議 ] LeetCode 1290. Convert Binary Number in a Linked List to Integer #105
-
|
原 issue: LeetCode: 再麻煩 @twy30 給予命名建議 orz 感激不盡 public class Solution
{
public int GetDecimalValue(ListNode head)
{
string valueInBinary = "";
while (head != null)
{
valueInBinary += head.val.ToString();
head = head.next;
}
return Convert.ToInt32(valueInBinary.ToString(),2);
}
}我其實不知道為什麼它 是對的/可以產生對的結果 😅。 原本我的程式碼跟討論區中的其中一篇很像,所以我就改一改,然後就對了 (#°Д°) ;也有想過要設中斷點,但是不知道怎麼寫 〒▽〒 。想說應該問,但不知道該怎麼表達 ಥ_ಥ,寫了一大串還請見諒 orz 感謝閱讀。 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
你好 😊 string valueInBinary = "";這也可以叫
while (head != null)
{
valueInBinary += head.val.ToString();
head = head.next;
}然後呼叫 return Convert.ToInt32(valueInBinary.ToString(),2);附帶一提,因為
LeetCode 應該有列出 /**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/把 public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}把 public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}
public class Solution
{
public int GetDecimalValue(ListNode head)
{
string valueInBinary = "";
while (head != null)
{
valueInBinary += head.val.ToString();
head = head.next;
}
return Convert.ToInt32(valueInBinary.ToString(),2);
}
}就可以自己寫測試,例如 LeetCode 原題裡的 "Example 1": class Program
{
static void Main()
{
var node1 = new ListNode { val = 1 };
var node2 = new ListNode { val = 0 };
var node3 = new ListNode { val = 1 };
node1.next = node2;
node2.next = node3;
var output = new Solution().GetDecimalValue(node1);
Console.WriteLine(output);
}
}這樣子就可以在自己的機器上設中斷點來除錯了 😊 |
Beta Was this translation helpful? Give feedback.
-
|
@twy30 感謝大大 orz |
Beta Was this translation helpful? Give feedback.
@LPenny-github
你好 😊
這也可以叫
valueAsBinaryString。while這段會蒐集val裡的數值,存在valueInBinary裡。然後呼叫
Convert.ToInt32()( https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=net-5.0#System_Convert_ToInt32_System_String_System_Int32_ ) ,讓Convert.ToInt32()知道valueInBinary.ToString()內含的「文字」是2進位表示法,將那些文字轉為Int32。附帶一提,因為
valueInBinary本身就已經是string,所以.ToString()是不必要的。 😊LeetCode 應該有列出
LstNode的定義: