Objective C- How to add digits in a number? - objective-c
How do I add the digits in a particular number for example if the number is 3234 the result should be 3+2+3+4 = 12?
Something along the lines of this should do it:
int val = 3234;
int sum = 0;
while (val != 0) {
sum += (val % 10);
val = val / 10;
}
// Now use sum.
For continued adding until you get a single digit:
int val = 3234;
int sum = val;
while (sum > 9) {
val = sum;
sum = 0;
while (val != 0) {
sum += (val % 10);
val = val / 10;
}
}
// Now use sum.
Note that both of these are destructive to the original val value. If you want to preserve it, you should make a copy or do this in a function so the original is kept.
Hope it is not your homework !
int sum = 0;
while (value!=0) {
sum += value % 10;
value = value / 10;
}
Related
Why doesn't this While loop work as intended?
Hey guys, newbie here. One question, can't understand why this while loop doesn't work even when I entered a int bigger than 9 to the variable num, the while loop should repeat itself until the expression is false, and it doesn't, no output even. Am I missing something here? Thanks in advance. fun main () { while(true) { println ("\nWrite a positive number: ") var num = readLine()!!.toInt() var sum = 0 if (num > 9) { while (num > 9) { var digit = num % 10 sum = sum + digit num = num / 10 } println("\nDigit Sum: $sum") } else if (num in 1..9) { println("\nDigit Sum for the number $num is $num") } else { println("\nInvalid input, try again.") } } }
The issue is that you are not summing the last num when it gets less or equal to 9. You can even simplify your code a bit. Try the following: fun main() { while(true) { println ("\nWrite a positive number: ") val insertedNumber = readLine()!!.toInt() var num = insertedNumber var sum = 0 while (num > 9) { val digit = num % 10 sum = sum + digit num = num / 10 } sum = sum + num println("\nDigit Sum for the number $insertedNumber is $sum") } }
You don't need to redeclare the variables every time var sum = sum + digit var num = num / 10 So simply remove var sum = sum + digit num = num / 10
Read a sequence of numbers of undefined size & print the largest number & position of its first occurrence
I need to read a sequence of numbers of undefined size & prints the largest number & the position of its first occurrence Can anyone help with this code: import java.util.Scanner fun main() { val scan = Scanner(System.`in`) val num = scan.nextInt() var max = Int.MIN_VALUE var pos = 0 var i = 1 do { if (max < num) { max = num pos = i } i++ } while (scan.hasNext()) print("$max $pos") }
You just need to read a new number in each iteration: import java.util.Scanner fun main() { val scan = Scanner(System.`in`) var max = Int.MIN_VALUE var pos = 0 var i = 1 while (scan.hasNext()) { // Read a new number here val num = scan.nextInt() if (max < num) { max = num pos = i } i++ } print("$max $pos") }
My solution to this task This is a simple task, it can be solved in a simple way without using a “java.util.Scanner”. You just need to read a new number in each iteration. fun main() { var pos = 0 var max = 0 var count = 1 while (true) { val input = readlnOrNull() if (input == null) break val num = input.toInt() if (pos == 0 || num > max) { max = num pos = count } count++ } print("$max $pos") }
How to write Kotlin code to store all odd numbers starting at 7 till 101 and print sum of them?
How to write Kotlin code to store all odd numbers starting at 7 till 101 and print the sum of them? My code goes like this: var sum:Int = 0 var num:Int? = null for(num in 7..101 ) if(num % 2 != 0) print("$num ") var result = sum + num num++ println("$result")
Simply filter the range 7..101 and sum the items: val total = (7..101).filter { it % 2 == 1 }.sum() println(total) Or use sumBy(): val total = (7..101).sumBy { if (it % 2 == 1) it else 0} println(total) Or first create a list of all the odd numbers and then get the sum: val list = (7..101).filter { it % 2 == 1 } val total = list.sum() println(total)
If you need to store them, just create a MutableList and add the odd numbers during the forEach execution var oddNumbersTotal = 0 (7..101).forEach { n -> if (n % 2 != 0) { oddNumbersTotal += n } } println(oddNumbersTotal)
You can also try this: val array = IntArray(48){2*it+1} print(array.sum())
Kotlin - The caracter literal does not conform expect type Int
I'm struggling with types with my program, I've been asked to do it in JS first and it worked fine but now I can't achieve the result. Do you think I should make another 'algorithm' ? In advance, thank you for your time. fun main(){ // the idea is to put numbers in a box // that cant be larger than 10 val data = "12493419133" var result = data[0] var currentBox = Character.getNumericValue(data[0]) var i = 1 while(i < data.length){ val currentArticle = Character.getNumericValue(data[i]) currentBox += currentArticle println(currentBox) if(currentBox <= 10){ result += Character.getNumericValue(currentArticle) }else{ result += '/' //var resultChar = result.toChar() // result += '/' currentBox = Character.getNumericValue(currentArticle) result += currentArticle } i++ } print(result) //should print 124/9/341/91/33 }
The result is actually of a Char type, and the overload operator function + only accepts Int to increment ASCII value to get new Char. public operator fun plus(other: Int): Char In idomatic Kotlin way, you can solve your problem: fun main() { val data = "12493419133" var counter = 0 val result = data.asSequence() .map(Character::getNumericValue) .map { c -> counter += c if (counter <= 10) c.toString() else "/$c".also{ counter = c } } .joinToString("") // terminal operation, will trigger the map functions println(result) } Edit: If the data is too large, you may want to use StringBuilder because it doesn't create string every single time the character is iterated, and instead of using a counter of yourself you can use list.fold() fun main() { val data = "12493419133" val sb = StringBuilder() data.fold(0) { acc, c -> val num = Character.getNumericValue(c) val count = num + acc val ret = if (count > 10) num.also { sb.append('/') } else count ret.also { sb.append(c) } // `ret` returned to ^fold, next time will be passed as acc } println(sb.toString()) }
If you want a result in List<Char> type: val data = "12493419133" val result = mutableListOf<Char>() var sum = 0 data.asSequence().forEach { val v = Character.getNumericValue(it) sum += v if (sum > 10) { result.add('/') sum = v } result.add(it) } println(result.joinToString(""))
Kotlin decomposing numbers into powers of 2
Hi I am writing an app in kotlin and need to decompose a number into powers of 2. I have already done this in c#, PHP and swift but kotlin works differently somehow. having researched this I believe it is something to do with the numbers in my code going negative somewhere and that the solution lies in declaring one or more of the variable as "Long" to prevent this from happening but i have not been able to figure out how to do this. here is my code: var salads = StringBuilder() var value = 127 var j=0 while (j < 256) { var mask = 1 shl j if(value != 0 && mask != 0) { salads.append(mask) salads.append(",") } j += 1 } // salads = (salads.dropLast()) // removes the final "," println("Salads = $salads") This shoud output the following: 1,2,4,8,16,32,64 What I actually get is: 1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,-2147483648, Any ideas?
This works for the one input that you specified, at the very least: fun powersOfTwo(value :Long): String { val result = ArrayList<String>() var i = 0 var lastMask = 0 while (lastMask < value) { val mask = 1 shl i if (value != 0.toLong() && mask < value) { result.add(mask.toString()) } lastMask = mask i += 1 } return result.joinToString(",") } Ran it in a unit test: #Test fun addition_isCorrect() { val result = powersOfTwo(127) assertEquals("1,2,4,8,16,32,64", result) } Test passed.
You can get a list of all powers of two that fit in Int and test each of them for whether the value contains it with the infix function and: val value = 126 val powersOfTwo = (0 until Int.SIZE_BITS).map { n -> 1 shl n } println(powersOfTwo.filter { p -> value and p != 0}.joinToString(",")) // prints: 2,4,8,16,32,64 See the entire code in Kotlin playground: https://pl.kotl.in/f4CZtmCyI
Hi I finally managed to get this working properly: fun decomposeByTwo(value :Int): String { val result = ArrayList<String>() var value = value var j = 0 while (j < 256) { var mask = 1 shl j if ((value and mask) != 0) { value -= mask result.add(mask.toString()) } j += 1 } return result.toString() } I hope this helps someone trying to get a handle on bitwise options!
Somehow you want to do the "bitwise AND" of "value" and "mask" to determine if the j-th bit of "value" is set. I think you just forgot that test in your kotlin implementation.