Skip to content

Commit

Permalink
Add new bit manipulation and linked list example
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Jan 4, 2024
1 parent 3013b1d commit dbb68b9
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 5 deletions.
29 changes: 29 additions & 0 deletions golang/1290.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package golang

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/

type ListNode struct {
Val int
Next *ListNode
}

func getDecimalValue(head *ListNode) int {
result := 0

for head != nil {
// shift bits to right
result = result << 1
// do a bitwise or operation
// 100 | 001 -> b101 -> 5
result = result | head.Val
head = head.Next
}

return result
}
16 changes: 16 additions & 0 deletions golang/1290_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package golang

import "testing"

func TestFirstGetDecimalValue(t *testing.T) {
last := ListNode{Val: 1}
middle := ListNode{Val: 0, Next: &last}
head := ListNode{Val: 1, Next: &middle}

result := getDecimalValue(&head)
expected := 5

if result != expected {
t.Fatalf(`getDecimalValue(%v) = %v, expected: %v`, head, result, expected)
}
}
11 changes: 6 additions & 5 deletions golang/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
| Problem Number | Tag | URL |
| -------------- | ------------- | ------------------------------------------------------------------------------------ |
| 888.go | Hash table | https://leetcode.com/problems/fair-candy-swap |
| 1608.go | Binary Search | https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ |
| 1539.go | Binary Search | https://leetcode.com/problems/kth-missing-positive-number/ |
| Problem Number | Tag | URL |
| -------------- | ------------------------------ | ------------------------------------------------------------------------------------ |
| 888.go | Hash table | https://leetcode.com/problems/fair-candy-swap |
| 1290.go | Linked List / Bit manipulation | https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer |
| 1539.go | Binary Search | https://leetcode.com/problems/kth-missing-positive-number/ |
| 1608.go | Binary Search | https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/ |

0 comments on commit dbb68b9

Please sign in to comment.