How to check if a number overflows an 'int'
(I looked at the possible duplicate to this question and I'm uncertain how useful that reading will be, since in an interview context, you'd be expected describe the general ideas / approach)
Part of answering interview questions is to ask clarifying questions (one of the important checklist items that interviewers expects from you).
So your line of inquiry should at least include things like:
- Are you allowed to use
unsigned long long
/uint64_t
(64 bit int)? - Where is the string coming from?
stdin
/ read from file / hard-coded as a string literal? - Is it given to you as a Decimal representation? Binary / Octal / Hex?
- What kind of error should be thrown? Do we try to recover and continue execution? What's the fail-safe default value?
Assuming that your interviewer tells you that it's in Decimal representation + you can use unsigned long long
:
- First check the number of digits: 32-bit
unsigned int
ranges between0 to 4,294,967,295
. If the number's string representation in decimal has more than 10 characters (has more than 10 digits), it already overflows; raise error. - Next, save the number into an
unsigned long long
and divide byUINT32_MAX+1=4294967296
. If the result is greater than0
, it overflows; raise error.
Why does the value from NSFileSystemFreeSize differ from the free size reported in the iOS Settings?
I bet that you are using 32-bit integer or float types to store your file system size values. This will fail with large enough file sizes. Instead, use unsigned long long or long double types to store these values.
See the corrected version of this answer for how to read these file sizes accurately. The comments on that answer and others there indicate that this returns a value which matches the free size reported by iTunes and other tools.
Get file size in Swift
Use attributesOfItemAtPath
instead of attributesOfFileSystemForPath
+ call .fileSize() on your attr.
var filePath: NSString = "your path here"
var fileSize : UInt64
var attr:NSDictionary? = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: nil)
if let _attr = attr {
fileSize = _attr.fileSize();
}
In Swift 2.0, we use do try catch pattern, like this:
let filePath = "your path here"
var fileSize : UInt64 = 0
do {
let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)
if let _attr = attr {
fileSize = _attr.fileSize();
}
} catch {
print("Error: \(error)")
}
In Swift 3.x/4.0:
let filePath = "your path here"
var fileSize : UInt64
do {
//return [FileAttributeKey : Any]
let attr = try FileManager.default.attributesOfItem(atPath: filePath)
fileSize = attr[FileAttributeKey.size] as! UInt64
//if you convert to NSDictionary, you can get file size old way as well.
let dict = attr as NSDictionary
fileSize = dict.fileSize()
} catch {
print("Error: \(error)")
}
Is there a constraint that restricts my generic method to numeric types?
C# does not support this. Hejlsberg has described the reasons for not implementing the feature in an interview with Bruce Eckel:
And it's not clear that the added complexity is worth the small yield that you get. If something you want to do is not directly supported in the constraint system, you can do it with a factory pattern. You could have a
Matrix<T>
, for example, and in thatMatrix
you would like to define a dot product method. That of course that means you ultimately need to understand how to multiply twoT
s, but you can't say that as a constraint, at least not ifT
isint
,double
, orfloat
. But what you could do is have yourMatrix
take as an argument aCalculator<T>
, and inCalculator<T>
, have a method calledmultiply
. You go implement that and you pass it to theMatrix
.
However, this leads to fairly convoluted code, where the user has to supply their own Calculator<T>
implementation, for each T
that they want to use. As long as it doesn’t have to be extensible, i.e. if you just want to support a fixed number of types, such as int
and double
, you can get away with a relatively simple interface:
var mat = new Matrix<int>(w, h);
(Minimal implementation in a GitHub Gist.)
However, as soon as you want the user to be able to supply their own, custom types, you need to open up this implementation so that the user can supply their own Calculator
instances. For instance, to instantiate a matrix that uses a custom decimal floating point implementation, DFP
, you’d have to write this code:
var mat = new Matrix<DFP>(DfpCalculator.Instance, w, h);
… and implement all the members for DfpCalculator : ICalculator<DFP>
.
An alternative, which unfortunately shares the same limitations, is to work with policy classes, as discussed in Sergey Shandar’s answer.
What is the difference between int, Int16, Int32 and Int64?
Each type of integer has a different range of storage capacity
Type Capacity
Int16 -- (-32,768 to +32,767)
Int32 -- (-2,147,483,648 to +2,147,483,647)
Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
As stated by James Sutherland in his answer:
int
andInt32
are indeed synonymous;int
will be a little more
familiar looking,Int32
makes the 32-bitness more explicit to those
reading your code. I would be inclined to use int where I just need
'an integer',Int32
where the size is important (cryptographic code,
structures) so future maintainers will know it's safe to enlarge an
int
if appropriate, but should take care changingInt32
variables
in the same way.The resulting code will be identical: the difference is purely one of
readability or code appearance.
How to get file size properly and convert it to MB, GB in Cocoa?
For converting file size to MB, Gb use below function
- (id)transformedValue:(id)value
{
double convertedValue = [value doubleValue];
int multiplyFactor = 0;
NSArray *tokens = @[@"bytes",@"KB",@"MB",@"GB",@"TB",@“PB”, @“EB”, @“ZB”, @“YB”];
while (convertedValue > 1024) {
convertedValue /= 1024;
multiplyFactor++;
}
return [NSString stringWithFormat:@"%4.2f %@",convertedValue, tokens[multiplyFactor]];
}
EDIT:
You can also use NSByteCountFormatter class. Available in iOS 6.0 / OS X v10.8 and later.
[NSByteCountFormatter stringFromByteCount:1999 countStyle:NSByteCountFormatterCountStyleFile];
You can use NSByteCountFormatterCountStyleFile
, NSByteCountFormatterCountStyleMemory
, NSByteCountFormatterCountStyleDecimal
or NSByteCountFormatterCountStyleBinary
in countStyle.
NSByteCountFormatterCountStyleFile: Specifies display of file or storage byte counts. The actual behavior for this is
platform-specific; on OS X 10.8, this uses the decimal style, but that
may change over time.NSByteCountFormatterCountStyleMemory: Specifies display of memory byte counts. The actual behavior for this is platform-specific; on OS
X 10.8, this uses the binary style, but that may change over time.NSByteCountFormatterCountStyleDecimal: Specifies the number of bytes for KB explicitly, 1000 bytes are shown as 1 KB
NSByteCountFormatterCountStyleBinary: Specifies the number of bytes for KB explicitly, 1024 bytes are shown as 1 KB
Cannot calculate factorials bigger than 20! ! How to do so?
The limit on an unsigned long long is 18446744073709551615, or about 1.8e+19. 20! is about 2.4e+18, so within range, however 21! is about 5.1e+19, exceeding the maximum size of an unsigned long long.
You may find this helpful: Are there types bigger than long long int in C++?
Related Topics
Changing the Color of the Icons in a Uitextfield Inside a Uisearchbar
Swift. Is the (Absolutely) Sole Specific Advantage of Unowned Over Weak, Performance
Can Not Cast Value of Type Nstaggedpointerstring to Nsdictionary
Connecting Hc-05 with iPhone Se iOS(V11.0)
Swift 4.2, String Firstindex() Function Error in Xcode Playground
Swift Optionals - Why Does Var A:Int? A? = 4 Return Nil
How Set Custom Fonts for iOS13 Context Menu Actions
How to Create a Circle with Rounded Ends for Each Quadrant
How to Stop a Dispatchqueue in Swift
Making a Uibutton a % of the Screen Size
How to Delete Object in Array of Dictionaries Using Key Value
How to Make Prepareforsegue with Uicollectionview
Rotate a Sprite to Sprite Position Not Exact in Spritekit with Swift
Resizing Uimage When Using Sf Symbols - Uiimage(Systemname:)
Swiftui: Localizedstringkey with Indices
Enum's Rawvalue Property Not Recognized