Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Swift dec to hex (#5627)
Browse files Browse the repository at this point in the history
* Solves issue with swift not finding the largest two elements correctly

* Solves  #5560 Write a Scala program to convert temperature from celsius to kelvin

* Removes #5560 changes

* F# program to implement linear search (#5295)

* Solves 5173: Write a Haskell program to find the largest three elements in an array

* Create ConvertDecimalToHexadecimal.swift

Converts a decimal number to its hexadecimal representation.a

---------

Co-authored-by: David Fernandez <david@Davids-MacBook-Pro.local>
Co-authored-by: Harsh Raj <harshraj8843@gmail.com>
Co-authored-by: Anandha Krishnan S <anandajith@gmail.com>
Co-authored-by: Ritesh Kokam <61982298+RiteshK-611@users.noreply.github.com>
  • Loading branch information
5 people authored Apr 13, 2024
1 parent a0ba7f9 commit b6700ca
Showing 1 changed file with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
func decimalToHexadecimal(_ decimal: Int) -> String {
let hexDigits = "0123456789ABCDEF"
var hexString = ""
var number = decimal

while number > 0 {
let remainder = number % 16
if let hexDigit = hexDigits.character(at: remainder) {
hexString = String(hexDigit) + hexString
}
number /= 16
}

return hexString.isEmpty ? "0" : hexString
}

extension String {
func character(at n: Int) -> Character? {
return Array(self)[safe: n]
}
}

extension Array {
subscript(safe index: Int) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}

// Example usage
let decimalNumber = 255
let hexadecimalNumber = decimalToHexadecimal(decimalNumber)
print("Decimal: \(decimalNumber), Hexadecimal: \(hexadecimalNumber)"

0 comments on commit b6700ca

Please sign in to comment.