Posts

Showing posts with the label Numbers

Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0   class Solution {     public int searchInsert(int[] nums, int target) {                 int i = 0, length = nums.length;                 for(i=0;i<length;i++){             if(nums[i] >= target){                 return i;             }             }         return i;     } } Try it on Leetcode Here, we are iterating each element in arrays. While iterating to find perfect insert position, if current number is greater than or equal to target then that position will be result and no need to iterate further. If no position are found and we are at end of array , then last position will b

Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321   Example 2: Input: -123 Output: -321   Example 3: Input: 120 Output: 21   Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2 31 ,  2 31  − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. class Solution {     public int reverse(int x) {         StringBuilder sb;         String str = x+"";         int i;         if(x==0)             return 0;         if(x<0){             String sub1 = str.substring(0,1);             String sub2 = str.substring(1);             sb = new StringBuilder(sub2);             sb.reverse();             str = sub1+sb.toString();         }         else{             sb = new StringBuilder(str);             sb.reverse();             str = sb.toString();             for( i=0;i<str.length();i++){       

Happy Number - LeetCode

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example:  Input: 19 Output: true Explanation: 1 2 + 9 2 = 82 8 2 + 2 2 = 68 6 2 + 8 2 = 100 1 2 + 0 2 + 0 2 = 1       Here the solution has to be done with in-build method. If we squaring the sum of each digit it will end up at 1, but in another case if sum is 4 it will be on loop and doesn't end. So we have to break the loop at 1 or 4. If 1 it is happy number else it is not a happy number. Click this link to try it on Leetcode class Solution {     public boolean isHappy(int n) {         int sum=0, t1;         while(sum >= 0){             sum = 0;             while(n != 0){                 t1 = n%10;