/*
Approach
Using Bit Manipulation -
As we know XOR operation with 0 gives the same number
i.e, a XOR 0 = a
eg, for decimal no. 2=> 2 XOR 0 = 2
in binary, 010 XOR 000 = 010
Also we know that , XOR operation with same number gives 0
i.e, a XOR a = 0
eg, 2 XOR 2 = 0
in binary, 010 XOR 010 = 000
XOR is associative (like sum)
i.e, (2 XOR 3) XOR 4 = 2 XOR (3 XOR 4), So the order doesn't matter in performing XOR operation.
eg, 2^3^4^6 = 3^2^6^4 = 4^2^6^3 ......
So, using these three properties of XOR , we will solve the question. we will take ans variable with 0 as initial value. And then for each element i in array, we will perform the XOR operation of the element with 0, ans will become 0 if the same number is found (as a XOR a = 0) and so after the completion of the loop, only element with no duplicate number will remain and will be returned as ans.
*/
// https://leetcode.com/problems/single-number/description/
public class Solution {
public int SingleNumber(int[] nums) {
int ans=0; //since XOR with 0 returns same number
for(int i=0; i < nums.Length; i++){
ans ^= nums[i]; // ans = (ans) XOR (array element at i)
}
return ans;
}
}
-
MY PROJECTS
-
Recent Posts
- Algo. Java. Remove-duplicates-from-sorted-array
- Java.Hibernate.SimpleExample
- Java.Jdbc.SimpleExample
- SQL. Calc the sum with case, example
- Mullvad – free the internet :)
- Junit. Jupiter
- Java. SpringBoot Example how to work with dateTime in Specification
- Java.SpringBoot.PopularAnnotations
- SpringBoot. Exception Management
- Java.Hibernate.JoinTableAnnotation
- SpringBoot.Making our first starter and autoconfiguration
- Spring. Creating main annotation to start business logic
- Spring.Reading from properties file
- Spring.How to define spring version inside springBoot ?
- SpringBoot App inside Docker
- Kafka.FirstExperience
- Docker.MySql and Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0
- Gradle.Tips
- Spring.AppConfig
- Leetcode.Best-time-to-buy-and-sell-stock
Categories
- Aptana
- Azure
- C#
- DataSnap
- DBExpress
- Delphi
- Delphi и сети
- Delphi. Язык программирования
- ExtJS
- FastReport
- FireDAC
- FireMonkey
- GIT
- ICS
- IDE
- IIS
- Indy
- InnoSetup
- javascript
- jQuery
- JSON
- LiveBindings
- MSHTML
- MySQL
- PHP
- REST
- Ribbons
- SMS
- SQL инструкции
- SVN
- TRichView
- UniGui
- WebBroker
- WinAPI
- Windows
- Алгоритмы
- Без рубрики
- Деревья
- Ищу ответ
- Компонентостроение
- Мои компоненты
- Начальный уровень
- Обработка исключений
- Парсинг
- Потоки(Threads)
- Регулярные выражения
- Тестирование приложений