-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path136.Single_Number.rb
More file actions
120 lines (94 loc) · 2.3 KB
/
Copy path136.Single_Number.rb
File metadata and controls
120 lines (94 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# Given a non-empty array of integers, every element appears twice except for one.
# Find that single one.
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it
# without using extra memory?
# @param {Integer[]} nums
# @return {Integer}
def single_number(nums)
counts = Hash.new(0)
nums.each { |num| counts[num] += 1 }
counts.key(1)
end
# p single_number([1,1,"x",3,3,4,4])
# p single_number([1,3,5,2,3,1,5])
def single_number2(nums)
nums.reduce do |collect, num|
collect ^= num
end
end
# [1,3,5,2,2,1,5]
collect =
001
010
101
111
101
100
011
# 001
# 011
# 111
# 010
# 010
# 001
# 111
[3, 2, 3]
011
010
011
---
010
# p single_number2([1,1,"x",3,3,4,4])
# p single_number2([1,3,5,2,2,1,5])
#
# 12
num1 = 43434
# 10
num2 = 1345
# def bitwise_and(num1, num2)
# puts "num1 = " + num1.to_s(2)
# puts "num2 = " + num2.to_s(2)
# puts "base 10 & = " + (num1 & num2).to_s(10)
# puts "base 2 & = " + (num1 & num2).to_s(2)
# end
def bitwise_and(num1, num2)
bnum1 = num1.to_s(2)
bnum2 = num2.to_s(2)
band = (num1 & num2).to_s(2)
puts "num1 = " + ( ' ' * bnum2.length ) + num1.to_s(2)
puts "num2 = " + ( ' ' * bnum1.length ) + num2.to_s(2)
puts "b2& = " + ( ' ' * ([bnum1.length, bnum2.length].max ) + band)
# puts "base 10 & = " + (num1 & num2).to_s(10)
end
# bitwise_and(num1, num2)
def bitwise_or(num1, num2)
bnum1 = num1.to_s(2)
bnum2 = num2.to_s(2)
band = (num1 | num2).to_s(2)
puts "num1 = " + ( ' ' * bnum2.length ) + num1.to_s(2)
puts "num2 = " + ( ' ' * bnum1.length ) + num2.to_s(2)
puts "b|& = " + ( ' ' * ([bnum1.length, bnum2.length].min ) + band)
end
# bitwise_or(num1, num2)
def bitwise_not(num1)
bnum1 = num1.to_s(2)
band = (~num1)
length = (~num1).to_s(2).length
real_band = length.downto(0).map { |n| band[n] }.join('')
puts "num1 = " + num1.to_s(2)
puts "b~& = " + real_band
end
# bitwise_not(num1)
# 01101010101
# 01010111011
# -----------
# 00111101110
def bitwise_xor(num1, num2)
bnum1 = num1.to_s(2)
bnum2 = num2.to_s(2)
band = (num1 | num2).to_s(2)
puts "num1 = " + ( ' ' * bnum2.length ) + num1.to_s(2)
puts "num2 = " + ( ' ' * bnum1.length ) + num2.to_s(2)
puts "b|& = " + ( ' ' * ([bnum1.length, bnum2.length].min ) + band)
end